Use one response shape for success and failure so the browser does not have to parse custom text formats.
<?php
header('Content-Type: application/json; charset=utf-8');
$name = trim($_POST['name'] ?? '');
$errors = [];
if (mb_strlen($name) < 3) {
$errors['name'] = 'Enter at least 3 characters.';
}
echo json_encode([
'ok' => $errors === [],
'errors' => $errors
]);
?>Current approach first; the original XMLHttpRequest/AJAX examples below are retained and cleaned up for continued learning and legacy maintenance.
@$fname=$_POST['fname'];
@$sex=$_POST['sex'];
@$month=$_POST['month'];
@$agree=$_POST['agree'];
We set a flag to status 'OK' and at the end we will see if the $status_form is changed or not, if any of the validation fails then this status will change to NOTOK. We will also crate a variable to store the message and at the beginning it is kept blank.
$status_form = "OK";// Set a flag to check
$msg=""; // Message variable
$row=array("t1"=>"T","r1"=>"T","r2"=>"T","s1"=>"T","c1"=>"T","msg"=>"","status_form"=>"OK");
We have created one array with all the element status setting to T or validation is passed. As we check one by one element , we will change the status to false and add failure message to it. if(strlen($fname) < 3){
$row["status_form"]="NOTOK";
$row["t1"]="F";
$msg .= "Your Name must be more than 3 char length<br>";
}
See that if the valdation is not OK then we are changing the $status_form and the message we are adding the respective elements of the array
Similar way we have checked that the user has selected one of the two radio button by checking the variable sex. User must select one of the month so we have checked the variable $month. Finally we can check the status of the checkbox by checking its value is set to yes or not. If all the validations passed then the status of variable $status is checked ( OK or NOTOK) and output is given in green color font or in red color font.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.