v1.2.6 - Show latest stable - 2 notes - Class: ActionController::AbstractRequest
xml_http_request?() public

Returns true if the request's "X-Requested-With" header contains "XMLHttpRequest". (The Prototype Javascript library sends this header with every Ajax request.)

Show source
Register or log in to add new notes.
August 3, 2008 - (<= v2.1.0)
6 thanks

Cross browser issues

We use jQuery as our Javascript library of choice, but have to use a work around for full cross-browser support.

In jQuery you need to set the AJAX request headers as:


beforeSend: function(xhr) {xhr.setRequestHeader(“Accept”, “text/javascript”);}


But we found that IE and Safari sends headers like: HTTP_ACCEPT=>“text/html, /, text/javascript”, with the javascript header last so this mucks up the respond_to block as it will always enter the first block (usually format.html) and never reach your format.js block.

We have a before filter called on required actions that forces the request format to be javascript if it is an xml_http_request?

def fix_xml_http_request
  if request.xml_http_request?
    request.format = :js
August 6, 2008 - (<= v2.1.0)
1 thank

RE: Cross browser issues

In response to subblue’s note below, you should bear in mind that there may be circumstances where you want an AJAX request to enter the format.html block and not format.js.

When you’re returning HTML content, for example.

By using jQuery’s .ajaxSetup method in such an indiscriminate way (applying it by default to all ajax requests), you make it harder to keep track of what’s returning what.

A better alternative is to use it as a stored function;

function set_content_type_to_javascript(xhr) {
 xhr.setRequestHeader("Accept", "text/javascript");

and call this from within your .ajax requests when required;

 type: "GET",
 url: "/some/url",
 dataType: "script",
 beforeSend: function(xhr) { set_content_type_to_javascript(xhr) },etc…