0

I have a simple form validation I am doing. I am using AJAX to validate the user's email. When I console.log() the return value from the php script, it returns the correct value, but the ajax script... runs twice based on what I can tell from console logs.

Maybe I am doing this 100% wrong. But I have done this in the past and it works. I can't seem to get any Ajax call to work any more with basic Javascript because I run into the same error.

Something else that is odd.. I am also checking to see if the fields are empty and returning the form as false. When the form isn't fully filled out I see the correct output in the console. When I fully fill the form out. The AJAX query does the incorrect behavior.

function registrationCheck(){
var firstName = document.forms["registerForm"]["firstName"];
var lastName = document.forms["registerForm"]["lastName"];
var newAccount = document.forms["registerForm"]["newAccount"];
var email = document.forms["registerForm"]["email"];
var password = document.forms["registerForm"]["password"];
var verifyPassword = document.forms["registerForm"]["verifyPassword"];

var error = document.getElementById("registerError");
var errorMessage = "";

var formValidation = true;

if (firstName.value == "") {
    firstName.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}
if (lastName.value == "") {
    lastName.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}
if (newAccount.value == "") {
    newAccount.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}
if (email.value == "") {
    email.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}else{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            var answer = xmlhttp.responseText.trim();
            if (answer == "true") {
                errorMessage = "Email is in use";
                formValidation = false;
                console.log(formValidation);
                console.log("Answer:" + answer);
            }

        }
    }
    xmlhttp.open("GET", "../ajax.php?e=" + email.value, true);
    xmlhttp.send();
    console.log(formValidation);
}
if (password.value == "") {
    password.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}
if (verifyPassword.value == "") {
    verifyPassword.style.borderColor="red";
    errorMessage = "Please fill in all fields.";
    formValidation = false;
}


if (formValidation) {
    return true;
}else{
    error.innerHTML = "Please fill in all fields";
    return false;
}

}

<form action="../register" method="POST" role="form" name="registerForm" onsubmit="return registrationCheck()">
    <div class="form-group">
        <label for="firstName">First Name:</label>
        <input type="text" name="firstName" class="form-control" id="" placeholder="First name">
    </div>
    <div class="form-group">
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastName" class="form-control" id="" placeholder="Last name">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="text" name="email" class="form-control" id="" placeholder="Email Address">
    </div>
    <div class="form-group">
        <label for="newAccount">Account:</label>
        <input type="text" name="newAccount" class="form-control" id="" placeholder="Account name">
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" name="password" class="form-control" id="" placeholder="Password">
    </div>
    <div class="form-group">
        <label for="verifyPassword">Verify Password:</label>
        <input type="password" name="verifyPassword" class="form-control" id="" placeholder="Confirm your password">
    </div>
    <button type="submit" class="btn btn-primary">Register Account</button>
</form>
Jamie
  • 71
  • 6
  • 1
    Can you be more specific about how this "doesn't work"? Are you sure it's running twice? You do have two `console.log()` statements. What *specifically* is the indication of a problem? – David Aug 02 '16 at 23:47
  • If its running twice, probably a problem with how its being called. – developerwjk Aug 02 '16 at 23:49
  • @David - I shouldn't say it submits twice. I am using the wrong term I think... I can see two outputs of the formValidation variable with two different values, based on the script I provided above. If I remove the AJAX form and logic to check the email address, the form will work as intended. If the AJAX code is in place, the form will submit no matter what. – Jamie Aug 02 '16 at 23:51
  • @Jamie: What form? There's no form in the code posted here, or anything that would "submit", or anything that I would expect to prevent a form from submitting? Maybe the problem is in code you're not showing us? – David Aug 02 '16 at 23:51
  • @Jamie: `"I can see two outputs of the formValidation variable with two different values"` - That's because one of them executes before the AJAX response and the other executes after. The value is changing between those two things. – David Aug 02 '16 at 23:52
  • are you preventing the submission of the form in the page? or are you submitting it on a "submit" button and then again trying to submit the now empty form on an AJAX call? – gavgrif Aug 02 '16 at 23:52
  • @Jamie: In the `form` tag you have: `onsubmit="return registrationCheck()"` - What is `registrationCheck` and what does it return? If it returns `true` then the form will submit. – David Aug 02 '16 at 23:54
  • So I have it setup to set the formValidation to false if the prerequistes are not met, and then if that is false, the form returns false, or if they are met it returns true. @David - Sorry, wasnt finisinshed editing it :| The registrationCheck() function is the javascript I put at the top. – Jamie Aug 02 '16 at 23:55
  • @Jamie: Ok, and when you debug this, where does `formValidation` get set to `false`? Where specifically, stepping through the code in a debugger, does this fail? Basically, if the value starts as `true`, gets set to `false` in a bunch of `if` statements, and ends up still being `true` then it stands to reason that none of those `if` statements were true. – David Aug 02 '16 at 23:56
  • @David - The AJAX Call. (I am using chrome to manually debug this) (Output in console : js.js:52 true js.js:45 false js.js:46 Answer:true – Jamie Aug 02 '16 at 23:58
  • @Jamie: This is a duplicate of the linked question. You're returning the value before the AJAX call completes. – David Aug 02 '16 at 23:59
  • Oh - So just to clarify - come up with a way to delay the script until this ajax call is complete then continue through the script? – Jamie Aug 03 '16 at 00:01
  • 1
    @Jamie: No, artificially delaying the script is a famously bad idea. You don't want to *fight* the concept of asynchronous operations, but instead structure your code to use them effectively. The linked question has *far* better answers and examples than I can give :) – David Aug 03 '16 at 00:03
  • Thank @David - I appreciate your help! Take care! – Jamie Aug 03 '16 at 00:07

0 Answers0