1

I have a function:

var foo=function(){
var ret="false";
var data={};
data["blah"]="blah";
  $.ajax({

          type: "POST",

          url: "https://website.com/a",

          data: data,

          dataType: "json"

      }).success(function (data) {

          ret=data["stuff"];
         alert("set to "+ret);
      }).error(function (a, b, c) {
    alert("error");
        ret="false";
      });
return ret;
}

when I do the following: alert(foo());

I get the follow order of output:

1.false

2.set to true

I was expecting to get ret set to true and then returning false, but this is not what's happening. What am I doing wrong?

mugetsu
  • 4,228
  • 9
  • 50
  • 79
  • 2
    Please search for "asynchronous callback". This is a very common question. –  Jan 10 '12 at 18:21
  • http://stackoverflow.com/questions/6624325/jquery-ajax-request-return-value-undefined-inside-same-function , http://stackoverflow.com/questions/7070019/jquery-ajax-response-and-variable-assignment-problem , http://stackoverflow.com/questions/8077443/save-response-from-jquery-ajax-function , http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery –  Jan 10 '12 at 18:25

3 Answers3

3

The $.ajax is async by default. So basicly you return ret; earlier then javascript set it to ajax response.

Try to use async: false in $.ajax call options.

devdRew
  • 4,393
  • 3
  • 24
  • 33
  • If you truly want this behavior, sure ... :) A +1 just for pointing it out, although I would generally consider this approach "non ideal". –  Jan 10 '12 at 18:26
  • 3
    Be aware that setting `async : false` will freeze the user's browser until the response is received from the server. Depending on how long the AJAX request takes this could leave the user thinking their browser has crashed for several seconds or more. – Jasper Jan 10 '12 at 18:28
  • I'm not using `async: false`, it's the one of the main feature, there is no reason to make it `async: false` – devdRew Jan 10 '12 at 18:28
0

You cannot do this. The function will return before the AJAX call completes. It's asynchronous.

You cannot return from an AJAX function. I suggest moving all logic related to this AJAX call into the callback.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

Your success callback function will be called when the ajax response is received. This could be many milliseconds later, depending on network round-trip time. Your foo function does not wait for the callback to complete, but moves on immediately.

If you have actions to take that need the results of your AJAX call, you will need to perform those actions inside your success callback. This will probably require you to restructure your program.

Sean McMillan
  • 10,058
  • 6
  • 55
  • 65