Print PHP variables in different places in html

1

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);
    
asked by GhostOrder 24.07.2017 в 18:43
source

1 answer

1

Your idea of using arrays is very good, and in fact someone already had that idea before and from there came the idea of JSON. It is very easy to use and this is equivalent to using arrays in communications.

We will use the functions already implemented in PHP and JavaScript to achieve this goal, although everything could be done manually.

On the side of PHP, I suggest you use fixes because 1) you already have the intention to use fixes and 2) already there are functions implemented for handling fixes to JSON, so we can think of something like this:

PHP

$arreglo_respuestas = [];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  if(empty($_POST['name'])){
    $arreglo_respuestas["name"] = 'Name is required';
  }else{
    $name = test_input($_POST['name']);
  }
  if(empty($_POST['number'])){
    $arreglo_respuestas["number"] = 'Number is required';
  }else{
    $number = test_input($_POST['number']);
  }      
}
echo json_encode($arreglo_respuestas);

JS

var arreglo_respuestas = JSON.parse(phpRequest.responseText);

Then the variable arreglo_respuestas can be treated as a normal JavaScript array (which are also considered as objects) and you can get the values from there to put them where you want. For example:

var error_name = arreglo_respuestas.name;
var erro_number = arreglo_respuestas.number;

And somewhere else in your JS, you can assign those values to your span :

document.getElementById("spanName").innerHTML = error_name;
document.getElementById("spanNumber").innerHTML = erro_number;

P.D. In the last part I assumed that your span have ID, because it is the only way to easily differentiate them.

    
answered by 24.07.2017 / 19:50
source