I want to create a signup form that will validate your input and then send an AJAX request to a PHP page to check if your username has already been used. After that it will submit the actual form (the location is in an action attribute).
function validate() {
if (fullname.length < 90) { /*this is validating the form*/
var username_input = document.forms["myform"]["username"].value;
if (window.XMLHttpRequest) {
var usernamecheck = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var usernamecheck = new ActiveXObject("Microsoft.XMLHTTP");
}
usernamecheck.open("POST", "reciever.php", true);
usernamecheck.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
usernamecheck.send("user=" + username_input); /*sending username to check if it exists*/
usernamecheck.onreadystatechange = function() {
if (usernamecheck.readyState == 4 && this.status == 200) {
if (usernamecheck.responseText == "user") {
alert('username has already been used');
return false;
}
}
};
var contactcheck = new XMLHttpRequest(); /*second request*/
contactcheck.open("POST", "reciever.php", true);
contactcheck.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
contactcheck.send("contact=" + contactw);
contactcheck.onreadystatechange = function() {
if (contactcheck.readyState == 4 && this.status == 200) {
if (contactcheck.responseText == "contact") {
alert('email has already been used');
return false;
}
}
};
}
/*reference 1 (see below)*/
}
My problem is that the form submits even before the AJAX runs, and if I add return false; where the script says ‘reference 1’ the AJAX runs, but the form does not submit.