Thursday, October 11, 2012

Ajax Request in Ruby On Rails (UJS)



Many programmer uses jquery to catch click event and do $.get or $.post to access the server and print the response in a required div.

But there is a handy way to do ajax request using UJS provided by Rails .

Let us take an example of flipkart "add to wish list" event. So In flipkart.com when you click add to wish list , the item will be added in your wishlist .

This can be easily achieved in three easy steps.
Now lets see how to do that in rails using UJS

Step 1:
In view(show.haml.html) your may have
  
= link_to "Add to wishlist" , wish_list_path(@product) ,:id => "wish_list_link" 


Now we make it as ajax request by adding :remote => true
  
= link_to "Add to wishlist" , wish_list_path(@product) ,:id => "wish_list_link"  , 
:remote => true

Step 2:
Now in controller
    
    def wish_list
      #adding wish list 
      respond_to do |format|
         format.js #This line is important
       end
    end 
    


Step 3:
Now create a file named wish_list.js.erb
  
    $("#wish_list_link").html(''added to wishlist");
     # Lets say you want to render a partial .
    $("#wish_list_linkt").html('<%= escape_javascript(render :partial => "wish_list" , :locals => { :product => @product})%>');


Step 4(optional):
You can use jquery to show the loading part while server is responding
  
   $("#wish_list_link").live("click",function(){
        #show_loading_img
   })


...and that's it.

No comments:

Post a Comment