Click Upvote Click Upvote - 3 months ago 29
Ajax Question

Jquery getJson not calling callback

I have the following javascript code:

$.get("categories/json_get_cities/" + stateId, function(result)
{
//code here
}, 'json'
);


And the PHP code which processes it basically outputs something like this:

function json_get_cities($stateId)
{
//code here
echo json_encode(array('cities'=>$cities));
}


In the firebug console I can see that the ajax request is being made as expected, a 200 OK response is received, and a proper-seeming JSON object containing the cities is returned. However for some reason, the callback function I'm passing on to jquery is not being called.

Even putting a
debugger
call in at the top of the function, i.e

$.get("categories/json_get_cities/" + stateId, function(result)
{
debugger;
//code here
}, 'json'
);


doesn't work. However if I remove the 3rd argument of 'json' the function is then called (but the response text is treated as plain text instead of being a JSON object).

Here's the JSON response returned by the server:

{"cities":[{"id":"1613","stateId":"5","name":"Acton"}]}


Any thoughts?

Answer

Did you confirm that this is valid JSON? In jQuery 1.4 the JSON parsing is done in a strict manner, any malformed JSON is rejected and a parsererror is thrown.

Try console.log(arguments) in the callback to debug.

Also, you state that 'json' is the fourth argument, but it should be the third (as in your example).