Validate Web Forms with AJAX and PHP

Submit FormData without reloading the page

Browser-side checks improve feedback, but server-side validation remains authoritative. FormData can send the same field names as a normal form submission.

const form = document.getElementById('signupForm');
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const messageBox = document.getElementById('msgDsp');
  try {
    const response = await fetch(form.action, {
      method: 'POST', body: new FormData(form)
    });
    if (!response.ok) throw new Error('Request failed');
    const result = await response.json();
    const check = result.data[0];
    messageBox.textContent = check.msg;
    messageBox.style.borderColor = check.status_form === 'OK' ? 'green' : 'red';
  } catch (error) {
    messageBox.textContent = 'Validation service unavailable. Try again.';
  }
});
Current practice: keep client-side validation for user experience, but always repeat validation on the server. For database input, use PDO or MySQLi prepared statements.

The linked demo uses XMLHttpRequest to illustrate the request-response steps. The fetch() example above is an alternative for the same JSON validation endpoint. Both must handle server validation results and request failures.

A conventional PHP form can validate after a full-page submit. Server-side PHP validation protects the application even when the browser disables JavaScript, while client-side JavaScript validation provides earlier feedback. AJAX combines a background request with authoritative PHP validation.

AJAX sends form values to a PHP receiver without reloading the document. The receiver validates values and returns JSON, and JavaScript updates the existing form. Validation does not automatically create an account or save data.

  • The typed values remain visible while errors are displayed.
  • PHP checks data that browser-only rules cannot be trusted to verify.
  • The response provides field flags and a plain-text status message.

Ajax Validation onBlur
In this example we will use one each of all the form components. One text box , one set of radio buttons, one drop down list box and one checkbox will be used in our example so you can learn how to handle all type of components and use them as per your requirement.

Demo of PHP Ajax form validation
In this demo two files are used one is ajax-form-validation-demo.php and other one is ajax-form-validation-demo-code.php. Our ajax-form-validation-demo.php file stores all the Ajax and JavaScript codes along with the html form which is be validated. The file ajax-form-validation-demo-code.php file contains php code which receives the data and check the data. After checking, it returns JSON to ajax-form-validation-demo.php.

Check the demo first to see what are the html form components used.
You can also read how to handle the basic Ajax function and form data.

Let us see how the different form component are handled and data is sent by POST method. We will start with our text data.

The next four snippets explain manual URL encoding of different HTML control types. They are useful for understanding requests. The working demo uses new URLSearchParams(new FormData(form)) to collect all controls and encode them safely without a custom getFormData() function.

Collecting the text entered data

We have asked the user to give first name at input text box. The data entered by user can be collected by using this code.
// Manual encoding of a text field for application/x-www-form-urlencoded.
var val = myForm.fname.value;
myParameters.push('fname=' + encodeURIComponent(val));

Collecting radio button data

Read more on how to collect radio button data here. The equivalent manual radio-group code is:
// Read the selected value from the radio group.
var val = '';
for (var i = 0; i < myForm.sex.length; i++) {
  if (myForm.sex[i].checked) val = myForm.sex[i].value;
}
myParameters.push('sex=' + encodeURIComponent(val));

Drop down select box data

The equivalent manual dropdown code is:
// Read the selected option from a dropdown.
var val = myForm.month.options[myForm.month.selectedIndex].value;
myParameters.push('month=' + encodeURIComponent(val));

Checkbox checked or not.

An unchecked checkbox is absent from form data. A checked checkbox sends its value, which is yes in this demo.
// Unchecked checkboxes have no value in submitted form data.
if (myForm.agree.checked) {
  myParameters.push('agree=' + encodeURIComponent(myForm.agree.value));
}
When assembling the request manually, join the encoded parameters with & and send them with a POST request. Alternatively, FormData and URLSearchParams avoid manual encoding mistakes.

Use the msgDsp message region to display validation feedback. You can read more on how to manage message while using Ajax here.

The data we have posted will be processed through our PHP script and will be returned to our main page by using JSON string. Try to learn about JSON string here. We will discuss how to process the JSON string here.
The PHP endpoint returns a data array. Its first item contains r1, t1, s1, c1 and status_form. A value of F marks an invalid field. For example:
// The PHP response sets r1 to F if the radio selection is invalid.
const invalidRadio = myObject.data[0].r1 === 'F';
document.getElementById('r1').style.borderColor = invalidRadio ? 'red' : 'white';
The server returns a flag for each field group. Apply a visible validation style only when its flag is F; provide a text explanation too so color is not the only feedback. You can learn more on CSS border style here.

Apply the corresponding flag to the other field groups as well, and expose the invalid state through aria-invalid.

Status of form validation

We have one element status_form which is set to OK or NOTOK based on the validation of total form is cleared or not. Use this status to update the message box and mark invalid fields. For valid input, the endpoint returns OK and a short success message. The demo displays its result with a green border.
For invalid input, the endpoint returns NOTOK and a plain-text message. Use textContent when displaying that message:
// Treat server messages as text; never inject user-influenced HTML.
const result = myObject.data[0];
const messageBox = document.getElementById('msgDsp');
messageBox.style.borderColor = result.status_form === 'NOTOK' ? 'red' : 'green';
messageBox.textContent = result.msg;


Download the code of this demo

Next: PHP validation and JSON response.
Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer