views:

52

answers:

3

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?

+2  A: 

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).

David
Strangely enough it worked when i put in console.log, must've been a cache issue
Click Upvote
+2  A: 

Make sure the json is valid using this...

JSON Validator

ctrlShiftBryan
+2  A: 

Another way to debug some of these ajax problems is to use the .ajax method, passing GET as the method type, rather than the .get method. This will allow you to specify an error callback function in addition to a success method.

RenderIn