0
votes

I did research but end up stuck with my PHP AJAX Form. My form is working already but I want to add some user experience like change border to red when HTML input tag is empty or criteria didn't match.

This is my PHP, AJAX form works. I validated users input in server side via PHP, not client side then return errors if any in JSON format to my jQuery/Javascript code. I want to know which HTML input tags are empty or failed so I can add a class of those input tags.

This is my return JSON from PHP and I converted to JSON.parse n jQuery/Javascript code.

{
    "errors": [{
        "firstname": "Missing First name"
    }, {
        "lastname": "Missing Last name"
    }]
}

I checked response if there's error here my JS code

var json = JSON.parse(response);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
     // I want to call a function here that detect which input tags are empty then add a class.                
   }else {
       //execute other function
  }  

PHP code

<?php

$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : null;
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : null;

$errors = []; //array for errors
$noError = "No error found";
if(empty($_POST['firstname'])){
    $errors[]['firstname'] = 'Missing First name';
}else{
    $firstname = sanitizedData($_POST['firstname']);
}
if (empty($_POST['lastname'])) {
    $errors[]['lastname'] = 'Missing Last name';
}else{
    $lastname = sanitizedData($_POST['lastname']);
}


if(!empty($errors)){
    $result_array = array('errors' => $errors);
    echo json_encode($result_array);
    exit();
}else{
    echo json_encode($noError);   
}

//sanitized data from user inputs
function sanitizedData($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>
1
What is problem with the code?Eddie
Hi @Eddie, nothing wrong with my code, instead I need some help to detect if input tags are empty or validation failed.devjson

1 Answers

0
votes

I want to call a function here that detect which input tags are empty then add a class.

Add a common class to all the input that need to be validated. Inside the if statement call a function

Use document.querySelectorAll to get all the input element which need to be validate.Use forEach to iterate and check if it is empty. Then use classList.add to add an error class in it

function checkInput() {
  var getAllInput = document.querySelectorAll('.ipClass');
  getAllInput.forEach(function(item) {
    if (item.value === '') {
      item.classList.add('error')
    }
  })
}
.error {
  border: 1px solid red;
}
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<button onclick="checkInput()">Check</button>