Ruby on Rails AJAX

AJAX Introduction

AJAX stands for Asynchronous Javascript and XML. It is a mixture of several technologies and is an important part of Rails application. It allows client side changes without reloading the page.

Let us see the working of a normal web server. On typing a web address and clicking on search, the browser makes a request to the server. To assemble the searched page, it fetches all associated assets like JavaScript files, images and stylesheets. On clicking a link, same process is followed. This is called ‘request response cycle’.

JavaScript makes request to the server, and parse the response. It can update information on the page. On combining these two abilities, a web page can be made with JavaScript that can update just a part of itself, without loading full page from the server. This technique is called AJAX.

By default Rails ships with CoffeeScript.

Let us see an example code to make Ajax request using the jQuery library


  1. $.ajax(url: "/test").done (html) ->  
  2.   $("#results").append html  

The above code fetches data from “/test”, then appends the result to the div with an id of results.


Unobtrusive JavaScript

To handle attached JavaScript to the DOM, Rails uses “Unobtrusive JavaScript” technique. This is considered as the best technique within the frontend community.

This is called ‘Unobtrusive’ JavaScript because we do not mix JavaScript code into HTML. With this, we can easily add behavior to any link by adding data attribute. Lot of benefits add up like the entire JavaScript is served on every page, it means it’ll get downloaded on the first page load and then can be cached on every page after that.

Example

Let us see an example of performing Ajax on delete action.

Step 1 Create an application named item.

rails new item  

Step 2 Write the following command.

rails generate scaffold Itemm state:string country:string  

Step 3 Write migrate command.

rake db:migrate  

Step 4 Update your destroy action in aap/views/itemms/index.html.erb file by writing the following code:

:remote => true, :class => 'delete_itemm'   

  

<tbody>   

    <% @itemms.each do |itemm| %>   

      <tr>   

        <td><%= itemm.state %></td>   

        <td><%= itemm.capital %></td>   

        <td><%= link_to 'Show', itemm %></td>   

        <td><%= link_to 'Edit', edit_itemm_path(itemm) %></td>   

        <td><%= link_to 'Destroy', itemm, method: :delete, data: { confirm: 'Are you sure?' }, :remote => true, :class => 'delete_itemm' %></td>   

      </tr>   

    <% end %>   

  </tbody>

Step 5 Create app/views/itemms/destroy.js.erb file.

$('.delete_itemm').bind('ajax:success', function() {   

   $(this).closest('tr').fadeOut();   

});

Step 6 Go to controller file at app/controllers/itemms_controller.rb and write the following code.

def destroy   

   @itemm = Itemm.find(params[:id])   

   @itemm.destroy   

     

   respond_to do |format|   

      format.html { redirect_to item_url }   

      format.json { head :no_content }   

      format.js   { render :layout => false }   

   end   

     

end

Step 7 Start the Rails server.

rails s  

Step 8 Run it on localhost.

  1. http://localhost:3000/itemms  
Ruby on rails Ajax 1

Create an item as shown in the following snapshot.

Ruby on rails Ajax 2

It will create the item as shown below.

Ruby on rails Ajax 3

Click on Back button.

Ruby on rails Ajax 4

If you will click on Destroy link, a popup will be shown through AJAX. It will destroy this item from the list.

Ruby on rails Ajax 5

ADVERTISEMENT

ADVERTISEMENT

Click OK to delete the item finally.

Ruby on rails Ajax 6

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *