Ruby on Rails 2.1 AJAX - Ruby on Rails 2.1

What is AJAX?

Ajax (Asynchronous JavaScript and XML) is a suite of several technologies not a single technology. Ajax has as a feature of the following technologies

  • XHTML for markup of web pages
  • DOM for dynamic display and interaction
  • XML for data manipulation and interchange
  • CSS for styling
  • XMLHttpRequest for Data retrieval
  • JavaScript for to interconnect all this together

Ajax facilitates user to retrieve the data for a web page, for the entire page. User does not need to refresh the content.

When user works with the basic web architecture, it allows user to click a link or submit a form, which will be further submitted to the server and sends back a response, then user’s response will be displayed on a new page.

When user works with an Ajax-powered web page, it loads an Ajax engine in the background. Ajax engine is written in JavaScript which will be responsible to communicate with the web server and to display the results to the user. When user submits data using Ajax-powered form, the server returns an HTML fragment which contains the server's response and displays the user data same time. There is no need of refreshing it.

To find more about AJAX check through link AJAX Tutorial

How Rails Implements Ajax?

Rails, has easy and steady model for how it implements Ajax operations. Ajax operations works and displays the like any other basic web architecture but faster and displays user data in one operation.

Sequence of activities of Ajax operation

  • Trigger − Trigger could be any user operation, like clicking on a button or link or doing changes to the data on a form or in a field.
  • The web client calls the server: A JavaScript method, XMLHttpRequest sends the data associated with the trigger through an action handler to the server. Data can be anything like ID of a checkbox, the text entered in entry field or a saved form.
  • The server does processing: Server-side action handler sends the data to server and returns an HTML fragment to the web client.
  • The client receives the response: The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.

Following above steps is the easiest way to use Ajax in a Rails application. User needs create custom JavaScript in the browser to perform more involved interactions, like server responses to any kind of data using an Ajax request

AJAX on Rails Example

Let’s go back to our Library example, where created table called subject and also added few subjects at the time of Migration. As of now we haven’t provided with procedure to add and delete subjects in this table.

Here let’s use Ajax on our library by providing list, show and create operations to subject table.

Creating Controllers

Controller for subject can be created by following the below

Above command creates a controller file app/controllers/subject_controller.rb. To have the following content, open the saved controller file and modify using any test editior.

Implementation process for all these functions will be as same as mentioned in the earlier chapters.

The list method implementation

This method will be used to list down all the subjects available in our database.

The show method implementation

This method will be used to display a particular subject corresponding to pass ID.

The create method implementation

The above code is not redirecting the page to any other page but just rendering only changed part instead of whole page.

This can be written using partial, no need to write a complete view file, just write a partial in /app/view/subject directory.

This will be the final controller file /app/controllers/subject_controller.rb which looks as below

Now create view files for other methods.

Creating Views

Let’s create view files for all the methods but not for create method, Create file will be created using a partial.

Creating view for list method

Create a file list.html.erb in /app/view/subject and populate it with the below code.

Here, iterating through the @subjects array and outputting a <li> element containing a link to the subject it is referencing for each item in the array. Additionally, you are outputting the number of books in that specific subject inside parentheses. Rails' associations make it easy to step through a relationship and get information like this.

Once done try browsing the Subject list using http://localhost:3000/subject/list. This will display the following screen.

list-subjects-ajax

Before testing above, make sure the Web Server is up and running

Creating view for show method

Create a file show.html.erb in /app/view/subject and populate it with the following code.

Here, by clicking on any subject user can find a listing of all the books available under specified subject.

Creating view for create method

create method will be created using partial instead of view, which will be discussed in the next chapter.

Adding Ajax Support

Using necessary JavaScript files in the layout user can get Ajax support in the Rails application.

Rails is bundled with numerous libraries, which make using Ajax in Rails is easy. Two libraries prototype and script.aculo.us are very popular.

For the libraries support (Prototype and script.aculo.us) to the application, Can be done adding standard.html.erb layout file in app/views/layouts then add the following line before the </head> tag, and save changes

This includes both the Prototype and script.aculo.us libraries in the template so their effects will be accessible from any of the views.

Now add the following code at the bottom of app/views/subject/list.html.erb

Here, link_to_function would be used instead of link_to method, as the link_to_function method enables user to harness the power of the Prototype JavaScript library to do some neat DOM manipulations.

Second section is the creation of the add_subject <div>, its visibility should be hidden by default using the CSS display property. The link_to_function is will change its property and show the <div> to the user to take input as required to add a new subject.

Now create Ajax form, using the form_remote_tag, which is similar to Rails helper form_tag tag, but it’s helps here to let the Rails framework know that it needs to trigger an Ajax action for this method. The form_remote_tag takes the :action parameter just like form_tag.

There are two additional parameters :update and :position.

  • :update parameter tells Rails' Ajax engine which element to update based on its id. In this case, it's the <ul> tag.
  • :position parameter tells the engine where to place the newly added object in the DOM. You can set it to be at the bottom of the unordered list (:bottom) or at the top (:top).

Now, create the standard form fields and submit buttons discussed as before and wrap things up with an <% end %> to close the <form> tag with equivalent </form> tag. Make sure that things are semantically correct and valid XHTML.

Creating partial for create method

We are creating partial for create method to add a subject and inside using one partial.

Under app/views/subject, create a new file named _subject.html.erb. and note that all the partials are should be named with an underscore (_) at the beginning.

Add the below code into this file the created partial file

User can now easily add several subjects without refreshing the page after each subject is added.

Once added, try browsing Subject list using http://localhost:3000/subject/list, which will be displayed as shown below

add-subject

Try adding subject in the name field and click on Add button, added subject would be displayed at the bottom of all available subjects; note that we are not refreshing the page here.


All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Ruby on Rails 2.1 Topics