0

I have a document.ready function like this;

  function myfun(){
    var xx;
    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: function(result) {
          xx = result;
        },
    });
    return xx;
  }


  var a;
  a = myfun();
  alert(a);

handle.php is set to echo 1234. But I am getting alert as "undefined". How can I fix this? Expected alert is "1234" (the reply from ajax handler).

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249

3 Answers3

1

It's asynchronous. Use a callback:

function myfun(){

    return $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false
    });
}

myfun().done(function(data){
    console.log(data);
});

Or if you're using an old jQuery version without deferred objects:

function myfun(done){

    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: done
    });
}

myfun(function(data){
    console.log(data);
});

https://stackoverflow.com/search?q=ajax+not+returning+data

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
0

Because you return the value before the ajax call can complete, ajax call are by default async, you can alert inside the success callback, at that point your variable will have the value you set:

function myfun(){
  var xx;
  $.ajax({
      type: 'POST',
      url: 'handler.php',
      cache: false,
      success: function(result) {
        xx = result;
        alert(xx);
      },
  });
}

myfun();
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
0

It is a problem of asynchronous calls. You can rewrite code such as:

var xx;
  var a;

  function myfun(){
    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: function(result) {
          xx = result;
        },
    });
  }

 myfun();
 alert(xx);
Alice
  • 144
  • 11