Tuesday, March 1, 2011

JQuery 1.5.1 and Converters

It appears that in 1.5 JQuery completely revamped the AJAX library. There appears to be a lot of nice features including indirect support for CORS and the withCredentials parameter. But there's a little landmine in there that I just ran into. It appears that part of the update was to include this new converter pattern which attempts to automatically convert responses based on the "dataType" you specify when creating a new $.ajax request. What I found is you are setting up an request like so:
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: successCallback,
  error: failureCallback
});              
the converter process will attempt to convert response using a "text script" converter, which intern attempts to write the response to the json request in a script block on the page. This ends up throwing an error to the extent of "Uncaught SyntaxError: Unexpected token :" The fix for all of this is to change the dataType for the request from 'json' to 'text json'. The response is then interpreted at the correct type and everyone is happy.

2 comments:

  1. This is ridiculous ... I have to go through a ton of js now.

    ReplyDelete
  2. This is not documented because this is false.

    One of your plugins (I'll guess validate), overrides ajax silently and breaks with 1.5. If you try with no plugin, you'll see the converter used is text to json.

    ReplyDelete