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.

7 comments:

  1. Great Post!
    Thanks a lot for sharing!
    I found this blog to be very useful!!
    JAVA training in Bangalore

    ReplyDelete
  2. I truly like your style of blogging. I added it to my preferred's blog webpage list and will return soon…data scientist course in malaysia

    ReplyDelete
  3. This post is very easy to read and appreciate without leaving any details. Great work! Great work!
    data science course in delhi

    ReplyDelete
  4. I was basically inspecting through the web filtering for certain data and ran over your blog. I am flabbergasted by the data that you have on this blog. It shows how well you welcome this subject. Bookmarked this page, will return for extra.
    what is hrdf

    ReplyDelete
  5. https://martininghamsoftdev.blogspot.com/2013/02/jquery-ajax-success-callback-not-firing.html?showComment=1597914638053#c8936412828790070135

    ReplyDelete
  6. I want to post a remark that "The substance of your post is amazing" Great work.
    best data science courses in hyderabad

    ReplyDelete