jQuery ajax callback not being called?

When replacing calls to some legacy ajax help functions, I recently came across a problem it took a while for me to resolve. According to Firebug (a very useful FireFox plugin, in case you don't know about it), the ajax call was made and the response looked perfectly fine, but my callback function was never invoked. In the end, for testing, I had a simple snippet like this:

$.get('/some/url', function(){ alert('called'); });

but I never saw the alert. After a bit of googling I found out that this could happen if the page at /some/url reports the wrong MIME type. Surely enough, after inspecting that page using LiveHTTPHeaders, it turned out that the content was delivered as "application/JSON", while in fact it was normal HTML and should be served as "text/html". I changed the content-type in the server page and everything started working again.

The reason for the problem is that jQuery tries to pass on the response to the callback in an intelligent way. If the response is JSON for example, it tries to build a javascript object and pass that to the callback instead of just providing the plain response text. If this interpreting of the response fails, like in my case when it tried to interpret HTML as JSON, jQuery seems to give up, never calling the callback function.

If you for some reason are not in control of the MIME type being served, there is another solution. Many of the jQuery ajax function accept an optional argument "dataType", telling jQuery how to interpret the response. The default for it is "Intelligent Guess" (based on the MIME type), but you can specify for example "xml", "html", or "JSON" instead.

Add new comment