I'm validating an html form with php and ajax. When there is an error, such as blank spaces, ajax prints the value of the variables that show those error messages.
The problem is that currently all the variables are printed in a single string, and I would like each error message to appear below the respective field. For example, 'Name is required' below the name field, 'Number is required' below the number field ... etc, for this I have prepared empty spans in my html.
What I suppose is that first I need to place all the variables in an array and call that array using ajax, but this last one is what is not done.
PS: I would like to solve this with pure javascript, without jquery.
JS
submitBtn.addEventListener('click', function(){
var phpRequest = new XMLHttpRequest();
phpRequest.open('POST', 'form.php');
phpRequest.onload = function(){
phpMessage.insertAdjacentHTML('beforeend', phpRequest.responseText);
}
phpRequest.send();
});
PHP
$nameErr = $numberErr = '';
$fieldsErr = array($numberErr, $numberErr);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST['name'])){
echo $nameErr = 'Name is required';
}else{
$name = test_input($_POST['name']);
}
if(empty($_POST['number'])){
echo $numberErr = 'Number is required';
}else{
$number = test_input($_POST['number']);
}
}
HTML
<form method="post">
<label>
<input type="text" name="name" placeholder="Your name*">
<span class="status-field-message"></span>
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
<span class="status-field-message"></span>
</label>
</form>
EDIT ---------------------
Thanks for your answer @Kenny, I think it works but it is printing 'undefined' instead of the strings that contain the variables, could you tell me what I'm doing wrong by implementing your answer in my code?
JS
submitBtn.addEventListener('click', function(){
myForm.onsubmit = function(event){
event.preventDefault();
}
var phpRequest = new XMLHttpRequest();
phpRequest.open('POST', 'form.php');
phpRequest.onload = function(){
var errorMessages = JSON.parse(phpRequest.responseText);
var errorName = phpRequest.nameErr;
var errorNumber = phpRequest.numberErr;
statusMessage[0].innerHTML = errorName;
statusMessage[1].innerHTML = errorNumber;
//statusMessage es el array que contiene todos los spans de mi html
}
phpRequest.send();
});
PHP
$nameErr = $numberErr = '';
$errors = [];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST['name'])){
$errors['nameErr'] = 'Name is required';
}
if(empty($_POST['number'])){
$errors['numberErr'] = 'Number is required';
}
}
echo json_encode($errors);