i want to create a signup form that will validate your input then it will send an ajax request to a php page to check if your username has already been used and after that it will submit the form.
my code is like this
function validate(){
if(fullname.length < 90){ /*this is validting 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 (you'll understand in the post)*/
}
now my problem is that the form submits even before the ajax runs, and if i put return false; where the script says ‘reference 1’ the ajax runs but the form does not submit
thanks in advance
i wold really help if this question could be shared with others for faster results
Having validation both in JavaScript and PHP typically leads to confusing problems, because it can be quite difficult to guarantee that both sets of validation works properly. Not just now, but also later on when changes are being made.
Usually the best process is to have only one validation, that you access in multiple ways.
For example, when you have some PHP validation code, that can be accessed via ajax to validate the form before it is submitted. There is no guarantee that JavaScript ever runs though, so it’s vital that PHP also validates the form that it receives.
That way, the PHP validation is the vital part of the process, and the ajax validation (using the same PHP code) helps to improve the user experience by giving good feedback before the form is submitted.
Hi @fagbemijeremiah_abuj, when validating the form asynchronously you always have to prevent the default submit event first; then later, when everything turns out to be valid, submit() the form from your code (this will not trigger any event handlers or internal constraint validation such as required attributes):
var form = document.getElementById('my-form')
form.addEventListener('submit', function (event) {
var xhr = new XMLHttpRequest()
var data = new FormData(form)
// Prevent submitting the form
event.preventDefault()
// Handle the validation response
xhr.addEventListener('load', function () {
if (xhr.responseText === 'error') {
// Something is wrong, show appropriate
// error indicators here
form.classList.add('error')
} else {
// Everything is fine, now we can actually
// submit the form
form.submit()
}
})
// Send the form data
xhr.open('POST', form.action)
xhr.send(data)
})
Actually, since you’re already sending the form data with AJAX anyway you might not need the dedicated submit but handle the form submission in one go on the server side. Then you’d just replace the form with a success message when there is no error, which can make for a nice UX. :-)
To me the simplest solution for username validation is just do it in javascript/ajax and then simply have an unique index (username) field using PDOException:
I do this for one of my websites:
public function register($data, $status) {
$db = DB::getInstance();
$pdo = $db->getConnection();
$this->pwd = password_hash($data['password'], PASSWORD_DEFAULT);
unset($data['password']);
try {
$this->query = 'INSERT INTO users (username, status, password, security, email, date_added) VALUES (:username, :status, :password, :security, :email, Now())';
$this->stmt = $pdo->prepare($this->query);
$this->result = $this->stmt->execute([':username' => $data['username'], ':status' => $status, ':password' => $this->pwd, ':security' => 'newuser', ':email' => $data['email']]);
} catch (\PDOException $e) {
//echo "unique index" . $e->errorInfo[1] . "<br>";
// an error occurred
/* if the error number is for something that this code is designed to handle, i.e. a duplicate index, handle it by telling the user what was wrong with the data they submitted
// failure due to a specific error number that can be recovered from by the visitor submitting a different value
return false;
else
// the error is for something else, either due to a programming mistake or not validating input data properly, that the visitor cannot do anything about or needs to know about
throw $e; // re-throw the exception and let the next higher exception handler, php in this case, catch and handle it
*
*/
if ($e->errorInfo[1] === 1062) {
return false;
} else {
throw $e;
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server:
}
return true;
}
That way is someone disables Javascript the username will be validated when the user submits the form still, plus it adds a little double protection in javascript (I think).
thanks, i understand where you are going to, i have created a logic which i use for serverside detection to know if JavaScript is disabled, i just don’t want people to keep going from page to page(if you understand what i mean)
just imagine you visit a page that uses almost 7 frameworks(just assuming) , which means that the page would be very heavy
and after 10 minutes it finally loads
then you type a username and it takes you to another page which takes even more time to load, then the page tells you that your username is taken
this is what i am trying to prevent(passing through to many pages)
That passing through many pages issue is only the underlying foundation that guarantees that all else failing, things will still work.
Everything else beyond that is about improving the user experience, which includes using ajax to validate and verify before the form is submitted, and potentially to also use ajax to submit the form and provide feedback without requiring a page load too.