-3

i would like to get string with getJSON function from my JSON document. I tried to return the value by everytime it return undefined. This is my code below. Thank you for your help.

 function getValues() {
       $.getJSON("layout.php",function(result){
         return result;    // this should be the return value
       });
 }


 var jsonString = getValues();
 alert(jsonString);

This is my layout.php document with JSON string

{"bigfield0":{"field0":{"collapse":"false"},"field1":{"collapse":"true"}},"bigfield1":{"field2":{"collapse":"false"}}}
adeneo
  • 312,895
  • 29
  • 395
  • 388
Bushwacka
  • 865
  • 4
  • 12
  • 22

3 Answers3

0

The $.getJSON is using a callback and does not return the value. It's a asynchronius function. You can watch the documentation on http://api.jquery.com/jquery.getjson/

Try to use this. That should return some data for you:

 function getValues() {
       $.getJSON("layout.php",function(result){
         alert(result);    // this should be the return value
       });
 }
cboxdk
  • 86
  • 2
0

The answer is that getJSON is an async method, so it does work and the rest of your code keeps running. At the time where you try to use the results, the getJSON is still in progress. The solution: callbacks

function getValues(callback) {
   $.getJSON("layout.php",function(result){
     callback(result);    // this should be the return value
   });
}

And call this:

getValues(function(values) {
    console.log(values);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

The third parameter in getJSON is an asynchronous call back function that cannot return a value. Also to print JSON object as a string, you need to serialize that object into string.

var jsonString = JSON.stringify(jsonObject)

Your overall code should be like this:

//Code before the GET.

$.getJSON("layout.php",function(result){
    var jsonString = JSON.stringify(result) //asuming result is a JSON object.
    // the remaining of your script.
});
Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21