Home » Ruby on Rails AJAX

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

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.

Step 2 Write the following command.

Step 3 Write migrate command.

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

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

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

Step 7 Start the Rails server.

Step 8 Run it on localhost.

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

Click OK to delete the item finally.

Ruby on rails Ajax 6


Download

Download this example

You may also like