Jake Wilson
Jake Wilson

Reputation: 91233

Return value from nested $.getJSON?

I have something like this:

var someJSON = function(){

  // Calculate some stuff here

  $.ajax({
    dataType: "json",
    url: "http://somewebsite.com/api/?callback=?",
    async: false,
    success: function(data) {
      return data; // How can I return this so that someJSON gets this value?
    }
  });

}();

console.log(someJSON); // I want someJSON to be = data from the ajax call

Essentially, I want someJSON to end up being the value of this json data that is returned via ajax. How do I return the value from the nested $.ajax call though? Can I use some sort of callback that the value gets passed back through?

Also I'm using async: false with this so that the rest of the script doesn't try to execute until someJSON has a value set. Is that the right way to do this?

Upvotes: 0

Views: 529

Answers (3)

SarathSprakash
SarathSprakash

Reputation: 4624

You can try like this

DEMO

function someJSON() {
   var resp = $.ajax({
    dataType: "json",
    url: "http://somewebsite.com/api/?callback=?"
   })
   .success(function (data) {
   });
   return resp;
};


someJSON().success(function (data) {
   console.log(data);
});

Hope this helps, Thank you.

Upvotes: 0

John Green
John Green

Reputation: 13445

You can only do this through a synchronous Ajax call:

var someJSON = function(){
  // Calculate some stuff here
  var retVal = null
  $.ajax({
    dataType: "json",
    url: "http://somewebsite.com/api/?callback=?",
    async: false,
    success: function(data) {
      retVal = data;
    }
  });
  return retVal;
};

console.log(someJSON());

HOWEVER, do this with caution. Generally speaking, it is better, safer, and faster to use asynchronous calls:

var someCalculatedObject = {};
function handleReturn(data)
{
   // process JSON.
}
$.ajax({
    dataType: "json",
    url: "http://somewebsite.com/api/?callback=?",
    async: true,
    data:someCalculatedObject
    success: handleReturn
  });

Upvotes: 1

Barmar
Barmar

Reputation: 782295

Since you're using async: false, you can simply set a variable and return it from the original function:

var someJSON = function(){
    var returnVal;

    // Calculate some stuff here

    $.ajax({
        dataType: "json",
        url: "http://somewebsite.com/api/?callback=?",
        async: false,
        success: function(data) {
            returnVal = data;
        }
    });
    return returnVal;
}();

However, you should think hard about whether you really need to use synchronous AJAX, as this can block the browser. You should learn the proper way to use asynchronous calls. See

How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Upvotes: 3

Related Questions