Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object ajax ajax

Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object


Here is a start:

First create your button with a link_to method in your view, for example:

=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'

Note that I am appending ".json" to the url of my resource. This is just an example of a an AJAX delete, google link_to to see the meaning of the parameters. The concept if that you make your HTTP request with the parameter :remote set to true, in other words this is translated to an AJAX call from your browser.

Second, write some javascript so that you can process what ever is the result of the AJAX call your browser will make when the user click on the link_to of step 1. For details you can see this blog post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

An example from my site:

jQuery(function($) {  // create a convenient toggleLoading function  var toggleLoading = function() { $("#loading").toggle() };  $("#pending_invitation")    .live("ajax:loading",  toggleLoading)    .live("ajax:complete", toggleLoading)    .live("ajax:success", function(event, data, status, xhr) {       var response = JSON.parse(xhr.responseText)       if (response.result == "ok") {          $(this).fadeOut('fast');       }       else {         var errors = $('<div id="error_explanation"/>');         errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');         $('#new_invitation_error').append(errors)          }    });});

where you can see that I parse the returned json and and change the html on the page based on that. Note that this js uses the CCS ids and classes defined in the top view that is not included here.

If you now want to write you own controller to spit out the json here is an example:

class InvitationsController < ApplicationController  respond_to :html, :json  # other methods here  # ...  def destroy    @invitation = Invitation.find(params[:id])    respond_to do |format|      if @invitation        @invitation.destroy        flash[:success] = I18n.t 'invitations.destroy.success'        format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }      else        format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }      end    end  endend

Hope this help.


Old question, but a really good overview of Ajaxifying Rails applications is:

Ajax in Rails 3.1 - A Roadmap


Also consider returning errors in the following format:

render :json => @myobject.to_json, :status => :unprocessable_entity

This will ensure that your client can process the response as an error.