-2

I have a small problem, I want to check if a user is logged in via AJAX POST to a PHP and then run the rest of the function, unfortunately the rest of the function is being ran without waiting for the AJAX to finish.. so that's bad news

function checkLogin() {
    dat = 'chl=1&x='+Math.random();
    $.ajax({
        url: "/action.php",
        type: "POST",
        data: dat,
        success: function(data) {
            if (data)
                return data;
            return 0;
        },
        error: function(data) {
            console.log('err'+data);
            return;
        }
    });     
}
function anotherFunction() {
      logged = checkLogin(); // is the user logged in?
      if (logged) {
         // do other stuff
         console.log('Logged in');
      } else {
         console.log('Not logged in..');
      }
}

So this is my problem, it says logged is undefined.. Is there any solution to this, besides using setTimeout, something more "natural" in terms of time of wait?

esqew
  • 42,425
  • 27
  • 92
  • 132
Crys Ex
  • 335
  • 1
  • 4
  • 9

2 Answers2

2

AJAX is asynchronous--do it in the success: code.

Reg Edit
  • 6,719
  • 1
  • 35
  • 46
-2

Make it a synchronous request by adding asynch parameter and set it to false [not recommneded]

$.ajax({
    url: "/action.php",
    type: "POST",
    data: dat,
    asynch: false,
    success: function(data) {
        if (data)
            return data;
        return 0;
    },
    error: function(data) {
        console.log('err'+data);
        return;
    }

[Recommended] call your desired method in success call back of Ajax call

    $.ajax({
    url: "/action.php",
    type: "POST",
    data: dat,
    success: function(data) {
        if (data)
            return data;
        yourDesiredFunctionHere();
        return 0;     

    },
    error: function(data) {
        console.log('err'+data);
        return;
    }
Abdul Hannan
  • 82
  • 1
  • 9
  • 1
    asynch? this is not the param you are looking for. Also setting it to that is a bad idea, re-factor the code. – rlemon Jul 01 '14 at 18:57
  • 2
    asynch is still not the property name ;) also your `yourDesiredFunctionHere` function is after the return statement so wouldn't hit. – rlemon Jul 01 '14 at 19:07