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;
}
?>