0

I have this function that I calling from within another function

function CheckForSession() {
        var str="chksession=true";

        jQuery.ajax({
                type: "POST",
                url: "chk_session.php",
                data: str,
                cache: false,
                success: function(res){
                    if(res == "0") {
                      alert('Your session has been expired!');
                    }
                }
        });
}

How can I make the entire function CheckForSession return false if the response equals 0?

P.S. In my application, the response to this function can only be either 1 or 0.

Nikita 웃
  • 2,042
  • 20
  • 45
  • you can't, as jQuery.ajax is asynchronous ... people will tell you to set `async:false` - but it's far better to learn how to write code that uses asynchronous behaviour properly – Jaromanda X Dec 07 '15 at 11:07
  • You should use the native http status codes. any error returned will make jquery fire the error event where you can handle the 403. it should be standard practice to check for any ajax request in you application. `header("HTTP/1.0 403 Unauthorized");` – synthet1c Dec 07 '15 at 11:12
  • You can pass a callback fn to the CheckForSession and in success/error of ajax you can decide to call or not to call – joyBlanks Dec 07 '15 at 11:22

1 Answers1

3

You can't do this because of asynchronous nature of AJAX requests.

The best solution for you is to use promises:

function CheckForSession() {
    var str="chksession=true";

    return jQuery.ajax({
            type: "POST",
            url: "chk_session.php",
            data: str,
            cache: false,
            success: function(res){
              blabla = res;
                if(res == "0") {
                  alert('Your session has been expired!');
                }
            }
    });
}

CheckForSession().then(function(data) {
    // successful
}, function() {
    // error
})

jQuery.ajax by default returns promise object, and i is resolved when ajax request will finished. Then you can write your actions depending on the result

http://api.jquery.com/jquery.ajax/

suvroc
  • 3,058
  • 1
  • 15
  • 29