Monday 11 February 2013

jQuery ajax success callback not firing

A form that uses jQuery to call a JSON returning action to populate a dependent dropdown on the change event of another dropdown no longer worked when the script registration changed to 1.4.4. It had been working previously with jQuery 1.6.4. (This would also apply to porting apparently working code to a new ASP.NET MVC 3 with earlier jQuery version.)

Having established that the success callback was no longer being fired, I added an alert to the error callback and found that the ajax call was generating the error "jQuery#####.##### was not called" (with some random numbers). This error is thrown when the ajax call parses the data returned by the URL (action) and determines that it is malformed according to the dataType property of the settings object parameter (in this case 'json'). jQuery 1.4.x is stricter than subsequent versions when parsing JSON, and the ajax call will throw the parse error if the JSON is not properly formatted - see jQuery API.

The MVC action returning JSON data contained the following line:

return Json((from r in roles select new { Value = r.Id.ToString(), Text = r.Title }).ToArray());

It looks like when MVC returns a JsonResult containing an array, the array is deemed by jQuery 1.4.x to be not properly formatted according to the JSON specification! Version 1.6.x masks this problem, otherwise for 1.4.x changing the dataType property of the settings object parameter of the ajax call from 'json' to 'text json' allows the call to succeed.