Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return json object in javascript function?

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?

like image 469
ptamzz Avatar asked Jan 11 '12 21:01

ptamzz


People also ask

What does JSON () return JavaScript?

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.

How do I display a JSON object?

Declare a JSON object and store it into variable. Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it.

What is JSON Stringify () method?

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.

How do I get JSON from fetch response?

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.


1 Answers

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
    });
});
like image 77
jAndy Avatar answered Oct 02 '22 00:10

jAndy