5

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?

1
  • Damn. Same problem as you but with latest Chrome. Edge is fine and JSON is valid. Commented Aug 31, 2016 at 10:50

4 Answers 4

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Strangely enough it worked when i put in console.log, must've been a cache issue
8

Make sure the json is valid using this...

JSON Validator

Comments

3

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.

Comments

1

Remember, JSON field names must be surrounded with quotes like the values when writing json in files for jquery to load. Ex:

In code:

{
  name: "value"
}

In JSON file:

{
  "name": "value"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.