0

I have a really simple jquery ajax call in a function, but I am getting a really weird error. It's a really simple functionality

function checkLogin() {
    $.ajax({
        url: "checkLogin.php",
        success: function(data) {
            alert(data); //this does print what I want to see
            return data; //this however returns undefined!
        }
    });
}

//some button onclick
var login_status = checkLogin(); 
alert(login_status); //shows undefined!
Patrick Mao
  • 1,013
  • 1
  • 8
  • 12
  • `ajax` is an `async` operation & your `alert(login_status);` is executed before your ajax is completed hence it will behave like this which is correct. – techie_28 Apr 11 '16 at 05:33

1 Answers1

0

This might help you out: Console log returning undefined

Basically, since AJAX is asynchronous, the alert will be called before the return statement.

You can either fix it by switching the order of the two expressions (or removing the alert altogether):

 $.ajax({
       url: "checkLogin.php",
       success: function(data) {
           return data;
           alert(data); 
         }
     });

... or make use of Promise interface:

  $.ajax({
       url : "checkLogin.php",
       success : function(data){
          return data;
          }
    }).then(function() { alert(data); });
Community
  • 1
  • 1
socialpiranha
  • 182
  • 1
  • 1
  • 10