I\'m trying to write a Rails controller method that will respond to get requests made both \"normally\" (e.g. following a link) and via ajax.
Normal Case: The controller
In your controller method, simply do this:
respond_to do |format|
format.js if request.xhr?
format.html { redirect_to :action => "index"}
end
In your controller dynamically select whether to use a layout based on request.xhr?
.
For example:
class SomeController < ApplicationController
layout :get_layout
protected
def get_layout
request.xhr? ? nil : 'normal_layout'
end
end
Another way of doing this would be to register new format and specify it explicitly in urls.
Put this in config/initializers/mime_types.rb
:
Mime::Type.register_alias 'text/html', :xhtml
Save your template in some_controller/some_action.xhml.haml
.
And add format to url:
http://mydomain.com/some_controller/some_action.xhtml
, or, better, use
url_for(:controller => :some_controller, :action => :some_action, :format => :xhtml)
or, even better, path helpers (if you are restful enough):
some_controller_some_action_imaginary_path(:format => :xhtml)
Mind, that no explicit respond_to
dispatching is required for this to work.
This technique might be an overkill if all you want is toggle layout for the same template, but if normal and ajax versions are different, then it is certainly a way to go.
EDIT:
The just released jQuery 1.5.1 brings the option to specify mime type in $.ajax()
:
mimeType: A mime type to override the XHR mime type.
This may be an alternative to explicit format in urls, though I haven't tried it yet.
If you're using a new version of rails you can just append .js onto the path and it will infer that the request is a JavaScript call