I've this function
function getTags(level){
$.getJSON("php/get-tags.php", { "parent": level }, function(json) {
return json;
});
}
I'm calling this function as
$(function(){
var tags = getTags('0');
});
The problems is, in the function getTags()
the return json
is like
{"tags":["Mathematics","Science","Arts","Engineering","Law","Design"]}
but at var tags = getTags('0')
, catching the return value, it gets an undefined
value.
Is the way I'm returning the value incorrect?
It returns a promise which resolves with the result of parsing the body text as JSON . Note that despite the method being named json() , the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.
Declare a JSON object and store it into variable. Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.
Like many others already correctly described, the ajax request runs asynchronous by default. So you need to deal with it in a proper way. What you can do, is to return the jXHR
object which is also composed with jQuery promise maker. That could looke like
function getTags(level){
return $.getJSON("php/get-tags.php", { "parent": level });
}
and then deal with it like
$(function(){
getTags('0').done(function(json) {
// do something with json
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With