Home > Rails, ruby > jQuery.load is a POST in IE but a GET in Firefox

jQuery.load is a POST in IE but a GET in Firefox

With a major thanks to JustinBall.com, I have finally figured out a major issue with a production app. That’ll teach me to not test in IE on PC.

So, what ends up happening is that a call to jQuery.load for some reason will be sent as a POST in IE. Of course, if you are using resources in Rails (which you should if you’re RESTful), this routes the HTTP call to the create action instead of the index action as you might assume.

For example:


jQuery(document).ready(function(){
jQuery("#ajax_table").load('/companies.js');
});

The code above will be sent to the create action of the CompaniesController instead of the index action.

Turns out (thanks again to Justin Ball) the issue comes from a JS trick that most Rails developers use to send along their AUTH_TOKEN in the jQuery Ajax call. I placed this code into my application.js


//This method makes sure that the AUTH_TOKEN is transmitted
jQuery(document).ajaxSend(function(event, request, settings) {
if (typeof(AUTH_TOKEN) == "undefined") return;
// settings.data is a serialized string like "foo=bar&baz=boink" (or null)
settings.data = settings.data || "";
settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

This ends up adding information to settings.data which is a problem since IE sees that and decides to send a POST instead of a GET. Justin’s ingenious fix is as follows:


jQuery(document).ajaxSend(function(event, request, settings) {
if (typeof(AUTH_TOKEN) == "undefined") return;
// This next line is the key!
if (settings.type == 'GET') return; // Don't add anything to a get request let IE turn it into a POST.
settings.data = settings.data || "";
settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: