AJAX

Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following −

  • XHTML for the markup of web pages
  • CSS for the styling
  • Dynamic display and interaction using the DOM
  • Data manipulation and interchange using XML
  • Data retrieval using XMLHttpRequest
  • JavaScript as the glue that meshes all this together

Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page.

When you interact with an Ajax-powered web page, it loads an Ajax engine in the background. The engine is written in JavaScript and its responsibility is to both communicate with the web server and display the results to the user. When you submit data using an Ajax-powered form, the server returns an HTML fragment that contains the server’s response and displays only the data that is new or changed as opposed to refreshing the entire page.

For a complete detail on AJAX, you can go through our AJAX Tutorial

How Rails Implements Ajax

Rails has a simple, consistent model for how it implements Ajax operations. Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web application) or trigger an Ajax operation −

  • Trigger − This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
  • Request − A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form.
  • Processing − The server-side action handler (Rails controller action) does something with the data and returns an HTML fragment to the web client.
  • 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.

These steps are the simplest way to use Ajax in a Rails application, but with a little extra work, you can have the server return any kind of data in response to an Ajax request, and you can create custom JavaScript in the browser to perform more involved interactions.

Example of AJAX

This example works based on scaffold; Destroy concept works based on AJAX.

In this example, we will provide, list, show and create operations on ponies table. If you did not understand the scaffold technology, then we would suggest you to go through the previous chapters first and then continue with AJAX on Rails.

Creating An Application

Let us start with the creation of an application It will be done as follows –

rails new ponies

The above command creates an application, now we need to call the app directory using with cd command.

cd ponies

It will enter into an application directory then we need to call a scaffold command. It will be done as follows −

rails generate scaffold Pony name:string profession:string

Above command generates the scaffold with name and profession column.

  • Model(app/models/pony.rb)
  • Controller (app/controllers/ponies_controller.rb)
  • Views (app/views/ponies/)
  • Routes

We need to migrate the data base with the following command −

rails db:migrate

Scaffolding adds the required routes in config/routes.db

Rails.application.routes.draw do
	resources :poniesend

Now Run the Rails application as follows command

rails server

Now open the web browser and call a URL as http://localhost:3000/ponies/new. The output will be as follows −

Rails And AJAX1

Click the Create Pony button, it will generate the result as follows –

Rails And AJAX2

Creating an Ajax

Now open app/views/ponies/index.html.erb with a suitable text editor. Update your destroy line with :remote => true, :class => ‘delete_pony’. It will look like as follows −

<table><thead><tr><th>Name</th><th>profession</th><th>colspan="3"</th></tr></thead><tbody>
  &lt;% @ponies.each do |pony| %&gt;
  &lt;tr&gt;&lt;td&gt;&lt;%= pony.name %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= pony.profession %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= link_to "Show", pony %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= link_to "Edit", edit_pony_path(pony) %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= link_to "Destroy", pony, method: :delete, data: { confirm: "Are you sure?" }, 
     :remote =&gt; true, :class =&gt; 'delete_pony' %&gt;&lt;/td&gt;&lt;/tr&gt;
  &lt;% end %&gt;
</tbody></table> <%= link_to "New pony", new_pony_path %>

Create a file, destroy.js.erb, put it next to your other .erb files (under app/views/ponies). It should look like this –

Rails And AJAX3

Now enter the code as shown below in destroy.js.erb −

$('.delete_pony').bind('ajax:success', function(){
	$(this).closest('tr').fadeOut();});

Now open your controller file which is placed at app/controllers/ponies_controller.rb and add the following code in the destroy method as shown below −

# DELETE /ponies/1.jsondefdestroy@pony=Pony.find(params[:id])@pony.destroy

	respond_to do|format|
		format.html { redirect_to ponies_url }
		format.json { head :no_content}
		format.js   { render :layout=>false}endend

It will finally look as follows −

classPoniesController<ApplicationController
	before_action :set_pony, only:%i[ show edit update destroy ]# GET /ponies or /ponies.jsondefindex@ponies=Pony.all
	end# GET /ponies/1 or /ponies/1.jsondefshowend# GET /ponies/newdefnew@pony=Pony.newend# GET /ponies/1/editdefeditend# POST /ponies or /ponies.jsondefcreate@pony=Pony.new(pony_params)

		respond_to do|format|[email protected]
			format.html { redirect_to @pony, notice:"Pony was successfully created."}
			format.json { render :show, status::created, location:@pony}else
			format.html { render :new, status::unprocessable_entity}
			format.json { render json:@pony.errors, status::unprocessable_entity}endendend# PATCH/PUT /ponies/1 or /ponies/1.jsondefupdate
respond_to do|format|[email protected](pony_params)
			format.html { redirect_to @pony, notice:"Pony was successfully updated."}
			format.json { render :show, status::ok, location:@pony}else
			format.html { render :edit, status::unprocessable_entity}
			format.json { render json:@pony.errors, status::unprocessable_entity}endendend# DELETE /ponies/1 or /ponies/1.jsondefdestroy@pony=Pony.find(params[:id])@pony.destroy!
respond_to do|format| format.html { redirect_to ponies_url } format.json { head :no_content} format.js { render layout:false}endendprivate# Use callbacks to share common setup or constraints between actions.defset_pony@pony=Pony.find(params.expect(:id))end# Only allow a list of trusted parameters through.defpony_params params.expect(pony:[:name,:profession])endend

Create a few ponies as shown below –

Rails And AJAX4

Till now, we are working on scaffold, now click the Destroy button, it will call a pop-up that works based on Ajax.

Rails And AJAX5

If you click the OK button, it will delete the record from pony. Final output will be as follows −

Rails And AJAX6

Comments

Leave a Reply

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