When I use jQuery (1.4.2) to execute a PUT request
$.ajax({ url: urlc, type: 'PUT', // POST + _method='PUT' makes no difference dataType: 'json', data: data,
against a Rails (3.0.0.beta4) controller using respond_with
def update @resource.update_attribute(...) respond_with(@resource) end
Then jQuery indicates an error even if Rails sends a success response.
Here's what's happening: ActionController::Responder#api_behavior responds with head :ok. Which in turn writes a response body containing a single space.
In the browser, jQuery, as requested, parses the response body, using its parseJSON function. If available, this function calls the native window.JSON.parse. Unfortunately, the later function, when called on the single space we got earlier, raises a SyntaxError. (It does the same on an empty string.)
I take it, the browser (Firefox 3.5.11) is to blame, but that doesn't help much. The easiest solution would be if jQuery didn't pass entirely whitespace strings to window.JSON.parse. As a stop-gap measure, I'm patching jQuery like this
var parseJSON_orig = $.parseJSON; $.parseJSON = function(data) { if (/^\s*$/.test(data)) { return null; } else { parseJSON_orig(data); } }
Is there any better way to get things working? Should jquery-ujs take care of this problem?
Michael