0

I am trying to understand how AJAX works. I have a problem in my code and I think it comes from the fact that AJAX is asynchronous (It might not be reason of the problem though). I am asking for your help to figure out what is wrong.

This is my javascript function. It calls a php page that check if the email is already in the database.

function validateEmail() {
    var email = $("#email").val();
    var isValid = false;

    if (email == "" || email.length == 0) {
        $("#emailresult").html("You must enter your email");
        isValid = false;
    } else if (email.length > 50) {
        $("#emailresult").html("Your email cannot have more than 75 characters");
       isValid = false;
    } else {
        $.post("checkemail.php", { email: email }, function(result) {
            if (result == 1) {
                alert("Inside result==1");
                $("#emailresult").html("Valid");
                isValid = true;
                alert(isValid);
            } else {
                alert("Inside result != 1");
                $("#emailresult").html("Already in use");
                isValid = false;
            }
        });
    }
    alert(isValid);
    return isValid;
}

Assume that checkemail.php returns 1. The alerts I have are:

  1. Inside result==1
  2. true
  3. false

So, in the end, the value returned is always false even if the email should be valid. Anyone can help me fix this?

Thank you!

Siwirt
  • 35
  • 4
  • 1
    Yes, you are correct. You can make ajax calls be synchronous, but isn't advised. – Mr Pablo Feb 06 '15 at 19:14
  • Your test is wrong, a string is being returned. `if (result == '1')` And [quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/) – Jay Blanchard Feb 06 '15 at 19:16
  • I was writing an answer, but I'll just say that you should keep the ajax call asynchronous and move everything that happens after the request to the callback, so you would `return isValid` from within it. – vcanales Feb 06 '15 at 19:17
  • This probably doesn't even matter, but I just have to say it.. You're comparing for characters greater than 50 and returning an error message saying it's over 75? :) – Aswin Ramakrishnan Feb 06 '15 at 19:18
  • @Jay Blanchard the php script returns an int.. well it "echo 1" – Siwirt Feb 06 '15 at 19:20
  • @devJunk I returned isValid within the AJAX call and it was working fine, but I was wondering if there was a way to just have 1 return call inside the function – Siwirt Feb 06 '15 at 19:22
  • @Aswin Ramakrishnan, yeah my bad. I'll have to correct this. I changed the size of the field in DB for email from 50 to 75, but I guess I didn't change the JS function – Siwirt Feb 06 '15 at 19:23
  • @Siwirt with the return on the callback should be enough, you don't need another one. – vcanales Feb 06 '15 at 19:24
  • Keep in mind that AJAX does not send and receive numbers, only text type things @Siwirt – Jay Blanchard Feb 06 '15 at 19:26

0 Answers0