2

I'm struggling in setting a function's return value to the json response of its ajax call.

function callMe() {    
    $.ajax({
        url: "someJson.php",
        type: "GET",
        dataType: 'json',              
        success: function(response){
            return response;
    }
}

 var jsonResponse = callMe();

How get I get jsonReponse to the hold the json response?

user784637
  • 15,392
  • 32
  • 93
  • 156

3 Answers3

1

This is not possible by default because ajax is asynchronous; therefore, once you send the ajax request, the function continues and does not wait until the ajax call returns before ending the function. It is best to do whatever you need to inside the success of the ajax call.

Edit:

You can make an ajax call synchronous, however, it is not recommended because it can lock up the browser.

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

jQuery Ajax Info

Josh Mein
  • 28,107
  • 15
  • 76
  • 87
1

Because the default behave of jquery ajax is async mode, you Can't directly get the response. At Least, You have two choice:

  1. pass the func as parameter into "callme":
function callMe(callback) {
   $.ajax({
      url: "someJson.php",
      type: "GET",
      dataType: 'json',              
      success: function(response){
          callback(response);
      }
   });
}

function dealResponse(response) {
  // do something with response
}

callMe(dealResponse);
  1. use sync mode ajax, and use your code directly get response and deal with it. but if you go this way, you script will block and may temporarily lock the browser when ajax request start, until the request end.
function callMe() {  
  var ret;

  $.ajax({
    url: "someJson.php",
    type: "GET",
    async
    dataType: 'json',              
    success: function(response){
      ret = response;
    }
  });

  retun ret;
}

var jsonResponse = callMe();

Hope these could help you :)

wedgwood
  • 1,064
  • 9
  • 10
-1

Do it like this:

function callMe() {  
    var result = false;  
    $.ajax({
        url: "someJson.php",
        type: "GET",
        async: false,
        dataType: 'json',              
        success: function(response){
            result = response;
            return response;
    } 
    return result;
}

var jsonResponse = callMe();
Tamik Soziev
  • 14,307
  • 5
  • 43
  • 55