0

I have a function which checks if there is a cookie session via an ajax call before the user adds of edits data the problem is that it takes too long to make the call to return the value in time so instead it always returns: undefined is there a way to run this function so that it will return the data in time? thanks for reading.

function checkSession(){
  $.get('/check_session.php',function(data){
      if(data == "loggedOut"){
         return "lo";
  }
}

function doSomething(){ //check if your logged in
   if(checkSession() == "lo"){ //always returns:undefined
      alert('your have been logged out');
   }else{ //do stuff

 }
}
user2014429
  • 2,497
  • 10
  • 35
  • 49

1 Answers1

0

1.It's not a problem with the server's response time. You have placed the return statement under the callback function that will be called asynchronously when $.get is done, so basically checkSession() will never return your expected value.

2.You have some options to resolve your problem: use $.deferred or turn your ajax method into a synchronous call. I personally choose the second one.

function checkSession(){
    return $.ajax({
        type: "GET",
        url: YOUR_URL,
        async: false
    }).responseText == "loggedOut" ? "lo" : "something";
}
foly
  • 197
  • 7