How to return json object in javascript function?

I have this function

function getTags(level){ $.getJSON("php/get-tags.php", { "parent": level }, function(json) { return json; }); } 

I call this function as

 $(function(){ var tags = getTags('0'); }); 

The problem is that in the getTags() function, return json is similar to

{"tags":["Mathematics","Science","Arts","Engineering","Law","Design"]}

but with var tags = getTags('0') , catching the return value, it gets an undefined value.

Do I believe the wrong value?

+4
source share
5 answers

Like many others that are already correctly described, the ajax request is executed asynchronously by default. Therefore, you need to deal with this properly. What you can do is return a jXHR object, which also consists of a jQuery promise maker. It might look like

 function getTags(level){ return $.getJSON("php/get-tags.php", { "parent": level }); } 

and then treat it like

 $(function(){ getTags('0').done(function(json) { // do something with json }); }); 
+5
source

You are trying to call an asynchronous function synchronously.

When you call getTags, it calls your PHP page call, if javascript blocks, then your page freezes until your server responds with JSON. You need to rethink your logic and call a callback.

 function getTags(level){ $.getJSON("php/get-tags.php", { "parent": level }, function(json) { //do something with the JSON here. }); } 
+2
source

You cannot return from an AJAX call. It is asynchronous. You need to have all the logic associated with the returned data in the callback.

+1
source

getJSON is asynchronous, the function it calls will be completed by the time the HTTP response returns and calls the callback.

You cannot return from it.

Use the callback to do what you want to do with the data.

+1
source

If you need this to work, your getTags function should return a value. This is currently not the case. You can achieve this by using $.ajax and setting async to false .

+1
source

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


All Articles