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 that 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 see that the ajax request is executing as expected, a 200 OK response is received, and a valid JSON object containing cities is returned. However, for some reason, the callback function I pass to jquery is not called.

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

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

does not work. However, if I delete the third argument to β€œjson”, then the function is called (but the response text is treated as plain text, not as a JSON object).

Here is the JSON response returned by the server:

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

Any thoughts?

+4
source share
4 answers

Have you confirmed that this is really JSON? In jQuery 1.4, JSON parsing is performed strictly, any rejected JSON is rejected and a parsererror is thrown.

Try console.log(arguments) in the callback for debugging.

You also indicate that "json" is the fourth argument, but it must be the third (as in your example).

+10
source

Make sure json is valid using this ...

JSON Validator

+7
source

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

+3
source

Remember that JSON field names must be surrounded by quotation marks, such as values ​​when writing json to files to load jquery. Example:

In code:

 { name: "value" } 

In the JSON file:

 { "name": "value" } 
+1
source

Source: https://habr.com/ru/post/1301362/


All Articles