3

I have a javascript function where I require it to verify some information from a database before proceeding. This is a simple boolean condition. If true, proceed, else terminate. The problem seems to be that the javascript function is immediately evaluating the function call as 'false', thereby terminating execution. It does this before the function actually returns, so even if the internal function returns true, the main function terminates incorrectly.

I'm still pretty new to js, php, and ajax. I'm guessing that this is a result of an asynchronous php call. Am I right about this conclusion? If so, is there a way to make the javascript function pause until it receives the results of the function call?

Here is my code. Thanks for any advice.

First, the main javascript function that gets called with the button onclick (in file 'users.php'):

function deleteUser() {

            //check for excessive inactivity
            if (verifySession()) {
                console.log("verified");
            } else {
                console.log("verification failed");  //<--line 33
                return false;
            }

            //continue on...

This is the function called by the if statement (in file 'session_handler.js'):

function verifySession() {

    var xmlhttp = new XMLHttpRequest();
                
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            var response = xmlhttp.responseText;
            console.log(response);                     //<--line 11
            if (response != "verified") {
                window.location.href = "signin.html";
                return false;
            } else {
                return true;
            }
        }
    }
            
    xmlhttp.open("GET", "scripts/verifySession.php", true);
    xmlhttp.send();
    return false;

}

And this is the output:

verified session_handler.js:11

verification failed users.php:33

So, you can see that the if condition outputs the string 'verified', and therefore is returning a 'true' result. But the main function is evaluating that to 'false', as evidenced by the string output 'verification failed'. What can I do to correct this?

Thanks!

3
  • You need to do verification on the server for any request that requires it, not on the client Commented Jul 6, 2013 at 18:32
  • 1
    That's why it's an ajax call to a php script. Commented Jul 6, 2013 at 18:34
  • You misunderstand; the verification needs to be done any time you are performing an action that is not idempotent. The ajax request won't prevent a user from requesting the target delete URL directly Commented Jul 6, 2013 at 18:51

3 Answers 3

1

It's because you're xmlhttp.onreadystatechange=function() is returning true, however, verifySession() is returning false here:

xmlhttp.open("GET", "scripts/verifySession.php", true);
xmlhttp.send();
return false;

My idea would be to do something like this:

function verifySession() {

var xmlhttp = new XMLHttpRequest();


var returnValue = xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        var response = xmlhttp.responseText;
        console.log(response);                     //<--line 11
        if (response != "verified") {
            window.location.href = "signin.html";
            return false;
        } else {

           return true;

        }
    }
}

xmlhttp.open("GET", "scripts/verifySession.php", true);
xmlhttp.send();
return returnValue;

}

I hope this Helps! :)

Sign up to request clarification or add additional context in comments.

1 Comment

That is a great idea. I would have never thought of it. Seems to solve the problem. Thanks a lot!
0

You cannot accomplish what you aim this way. In this code:

function deleteUser() {

            //check for excessive inactivity
            if (verifySession()) {
                console.log("verified");
            } else {
                console.log("verification failed");  //<--line 33
                return false;
            }

            //continue on...

The condition in whcih you're using verifySession() will always evaluate to false because no value is returned by this function by itself. Although you think you're returning a value from the onreadystatechange function, you really aren't. It is not being waited for by the initial function because you're sending it as an asynchronous request. Try using the following:

xmlhttp.open("GET", "scripts/verifySession.php", false);

But I must warn you that using synchronized ajax requests is not really a good idea. It may freeze browsers and stuff..

4 Comments

Thanks for the reply. I already tried setting that to false, but I got the exact same result.
@usr55410 well then you should really aim for a different approach. Easiest way is to have all of your main logic in the readystatechange function
I see what you are saying, though, about verifySession() always returning false. It's the very last line that is setting the return value, not the interior return statements, right?
Oh I didn't even notice that. Yes that is why it always returns false. Think of onreadystatechange as a whole different function that returns its own value which you're not really catching anywhere.
0

its impossible in javascript, since its doesnt wait for the ajax requests return value, all you can do is something like this...

deleteUser()

function deleteUser() {
  var callback  = function() {
    if ( this.readyState === 4 && this.status === 200 ) {
      var response  = this.responseText;
      console.log( response );
      if ( response !== "verified" ) {
        window.location.href  = "signin.html";
        console.log( "verification failed" );
      }
      else {
        console.log( "verified" );
        //continue on...
        // here all your other codes from 'deleteUser()'
      }
    }
  };
  verifySession( callback );
  return false;
}

verifySession()

function verifySession( callback ) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange  = callback;
  xmlhttp.open( "GET", "scripts/verifySession.php", true );
  xmlhttp.send();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.