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');
// Check types before reading values; do not suppress notices with @.
$fname = is_string($_POST['fname'] ?? null) ? trim($_POST['fname']) : '';
$row = ['t1' => 'T', 'status_form' => 'OK', 'msg' => ''];
if (!preg_match('/^.{3,80}$/uD', $fname)) {
$row['t1'] = 'F';
$row['status_form'] = 'NOTOK';
$row['msg'] = 'Enter a name between 3 and 80 characters.';
}
echo json_encode(['data' => [$row]]);
?>
This excerpt shows the response format. The linked ajax-form-validation-demo-code.php validates all four fields and returns the same data[0] structure.
// The complete endpoint first rejects array-valued fields.
$fname = is_string($_POST['fname'] ?? null) ? trim($_POST['fname']) : '';
$sex = is_string($_POST['sex'] ?? null) ? $_POST['sex'] : '';
$month = is_string($_POST['month'] ?? null) ? $_POST['month'] : '';
$agree = is_string($_POST['agree'] ?? null) ? $_POST['agree'] : '';
Initialize each field flag as passed (T). If any rule fails, change the appropriate flag to F, collect the messages, and set status_form to NOTOK.
$row = [
't1' => 'T', 'r1' => 'T', 'r2' => 'T',
's1' => 'T', 'c1' => 'T',
'msg' => '', 'status_form' => 'OK'
];
$messages = [];
The response array groups the status of each field with the overall form status. The browser reads these flags to mark the corresponding fields. if (!preg_match('/^.{3,80}$/uD', $fname)) {
$row['t1'] = 'F';
$messages[] = 'Enter a name between 3 and 80 characters.';
}
// Validate sex, month and agree in the same way.
if ($messages !== []) {
$row['status_form'] = 'NOTOK';
$row['msg'] = implode("\n", $messages);
}
The full endpoint also validates the radio choice, month and agreement checkbox. It returns one JSON object, whether the form passes or fails.
The server accepts only the two defined radio values, a month from 01 to 12, and a checked agreement value of yes. The client displays the JSON result as plain text and highlights invalid field groups.
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.