Rails detect if request was AJAX

Razor Storm picture Razor Storm · Nov 22, 2011 · Viewed 67.5k times · Source

In my action I wish to only respond with processing if it was called from an AJAX request. How do I check?

I want to do something like this:

def action
   @model = Model.find(params[:id])

   respond_to do |format|

      if (wasAJAXRequest()) #How do I do this?

         format.html #action.html.erb

      else

         format.html {redirect_to root_url}
   end
end

Answer

Amir Raminfar picture Amir Raminfar · Nov 22, 2011

You can check for a header[X-Requested-With] to see if it is an AJAX request. Here is a good article on how to do it.

Here is an example:

if request.xhr?
  # respond to Ajax request
else
  # respond to normal request
end