0

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?

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • @PHPglue He's using `async: false`, so it's not asynchronous. – Barmar Feb 08 '15 at 07:14
  • 1
    Please, please don't use synchronous ajax. Your users will thank you for NOT locking up their browser. – jfriend00 Feb 08 '15 at 07:18
  • When you return data from a callback function, it goes back to the caller of the callback (into the internals of ajax), not as a return value from your function. Whether your sync or async, returning a value from the success handler is NEVER the way to get an ajax value out to the outside world. – jfriend00 Feb 08 '15 at 07:19
  • See here for how to make this work with a proper asynchronous ajax call: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – jfriend00 Feb 08 '15 at 07:20

3 Answers3

3

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

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    I really think it's a disservice to help people solve problems with synchronous ajax calls without at least explaining the virtues and techniques to be used with a much better for the user asynchronous ajax call. Yes, I know that's what they asked, but people don't always ask the right question and often need to be steered in a better direction. – jfriend00 Feb 08 '15 at 07:22
1

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
  });
John Green
  • 13,241
  • 3
  • 29
  • 51
  • Neither one of your blocks of code works. The first is just wrong for an async call. The second isn't right even for a synchronous call. Maybe you got the async flag backwards in both? – jfriend00 Feb 08 '15 at 07:21
  • You have synchronous and asynchronous backwards in your two code blocks. – Barmar Feb 08 '15 at 07:23
  • I must have made them backwards. At least the text around them was correct. : ) – John Green Feb 08 '15 at 07:31
  • But how do I get this to work if the entire thing is wrapped in a closure like in my original example? A constraint is that `someJSON` variable is defined via a closure. In your example you can't do `return handleReturn()` since it's only going to run the callback after AJAX is complete, right? – Jake Wilson Feb 08 '15 at 15:08
  • I moved away from that, assuming it was a mistake on your part, since using a closure to populate a variable like that is weird -- and in this case, poor practice, since it makes the assumption that everything happens procedurally. In this (and many other) contexts you would have to force the system to work in a way that is unnatural to make it happen. Understand that if all AJAX was synchronous/blocking calls, the Web would be about 10x slower than it is. Use event-based programming where it makes sense, like when you make a call that may take an arbitrary amount of time to complete. – John Green Feb 08 '15 at 21:18
0

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.

SarathSprakash
  • 4,614
  • 2
  • 19
  • 35