I fed up looking for a clear and easy to digest Rails Ajax example. I wanted to know how to make a View and a Controller exchange data via Ajax in json format, so I made this post to help me and hopefully you to avoid the pain next time you need to implement such a thing! :D

In my scenario, a user clicks a li element in my web page (View). The text inside the li is a file name, stored somewhere in my server. Via Ajax, send that text (file name) to the Controller, return the contents of that file and display them in another part of the same web page (View).

This is a simple diagram of the whole procedure

Web page (View) -> Click on li element -> Pass the file name to Controller -> Let Controller/Model do their magic and return the file contents back to View -> Update View

In order to keep it simply, only the necessary parts of the code are shown.


For the following snippets of Rails code assume that the Model name is Script

Add the following javascript code in your view template (i.e. /app/views/scipts/show.html.erb in my case)

// /app/views/scipts/show.html.erb
<script type="text/javascript">
$(document).on("click", 'li', function() {
                 url: "<%= fileContent_script_path %>", // Route to the Script Controller method
                type: "GET",
            dataType: "json",
                data: { file_name: $(this).text() }, // This goes to Controller in params hash, i.e. params[:file_name]
            complete: function() {},
             success: function(data, textStatus, xhr) {
                        // Do something with the response here
                        editor.setValue(data.file_content) // Show the file contents in our editor.
                                                           // editor is defined somewhere above 
                                                           // 'file_content' is the key we use to respond
                                                           // in the controller function below
               error: function() {
                        alert("Ajax error!")

Implement the fileContent functionality in the controller

# /app/controllers/scripts_controller.rb
def fileContent
    @script = Script.where(:script_file_name => params[:file_name]).first # file_name is the data key of Ajax request in view

    if request.xhr?
        render :json => {
                            :file_content => @script.fileContent

Add in your routes.rb the Controller method responsible for the Ajax response

# /config/routes.rb
resources :scripts do

    member do
        get 'fileContent'

In a next post I will show you how to add mixed client/server side validation, for both file name and file extension.