Ajax Course

This tutorial shows how to Check and Validate input form field when loses focus (onblur event), with PHP via Ajax.
This script is useful when you want to check form field values with data stored on server, without refreshing the page.

    - To Download the script with the example presented in this tutorial, click: Validate input field with PHP via Ajax.

- Demo:
Valid data for this form: (Name = coursesweb; Password = mypass; E-mail = me@domain.com).
- When ALL the input fields are validated, the submit button is enabled and the form is Automatically submited.

• First, we create the HTML form. Each input field must be added into a <label>, <span>, or <div> element, together with a <span> tag with class="err", in this item it is added the error message associated to that input field.
- Example with a form with 3 input text fields, for Name, Password and E-mail:
<form action="some_script.php" method="post">
 <label for="exname">Name: <input type="text" id="exname" name="exname" /><span class="err"></span></label>
 <div>Password: <input type="password" id="expass" name="expass" /><span class="err"></span></div>
 <label for="exmail">E-mail: <input type="text" id="exmail" name="exmail" /><span class="err"></span></label><br/>
 <input type="submit" id="exsbm" disabled="disabled" value="Send" />
The idea is that both the input field and the item with class="err" must be added into a parent element, usually <label>, but can also be a <div> (like the password field from this example).

• Then we use the following JavaScript object with an Ajax function that is called when the input field is changed (detected when it loses focus, or on enter). The Ajax function sends the name and the value to a PHP script that checks and validates the received value.
If the response from the PHP script is not an empty string, the field is not valid, and the JavaScript object changes the CSS class of the input field, and adds the PHP response in the item with: class="err" associated to that field.
The field is valided when the PHP response is an empty string.

- To use this script, create an object instance of checkFormElm(), passing the ID of the submit button, and an array with the IDs of the input fields, like in this example:
/* HERE ADD THE checkFormElm() function */
// array with IDs of the fields to validate
var fields = ['exname', 'expass', 'exmail'];

// create an object instance of checkFormElm(), passing the ID of the submit button, and the $fields
var chkF = new checkFormElm('exsbm' fields);

JavaScript script with the Ajax function to check and validate form field

// object to validate form fields when they lose focus, via Ajax
// receives the ID of the Submit button, and an Array with the IDs of the fields which to validate
var checkFormElm = function(id_sbm, fields) {
  // from: https://coursesweb.net/ajax/
  var phpcheck = 'check.php';  // Here add the php file that validate the form element
  var elm_sbm = document.getElementById(id_sbm);  // the submit button
  var fields = fields || [];  // store the fields ID
  var elm_v = {};  // store items with "elm_name:value" (to know when it is changed)
  var err = {};  // stores form elements name, with value of -1 for invalid, value 1 for valid, and 0 for not checked

  // change the css class of elm
  var setelm = function(elm, val) {
    // if val not empty, sets in err an item with element name, and value of 1
    // sets border to this form element,
    // else, sets in err an item with element name, and value of 0, and removes the border
    if(val != '') {
      err[elm.name] = -1;
      elm.className = 'errinp';
      if(elm_sbm) elm_sbm.setAttribute('disabled', 'disabled');  // disables the submit
      elm.parentNode.querySelector('.err').innerHTML = val;  //  adds the error message
    else {
      err[elm.name] = 1;
      elm.className = 'vinp';
      elm.parentNode.querySelector('.err').innerHTML = '';  //  removes the error message

      // check if invalid or not checked items in $err (with value not 1)
      var inv = 0;
      for(var key in err) {
        if(err[key] != 1) {
          inv = 1;

      // if not invalid element, enables the submit button, and sends the form
      if(inv == 0 && elm_sbm) {

  // sends data to a php file, via POST, and displays the received answer
  var checkAjax = function(elm) {
    if(elm.value != '' && (!elm_v[elm.name] || elm_v[elm.name] != elm.value)) {
      elm_v[elm.name] = elm.value;  // store name:value to know if was modified
      var xmlHttp =  (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();  // gets the XMLHttpRequest instance

      // create pairs index=value with data that must be sent to server
      var  datatosend = elm.name +'='+ elm.value;
      xmlHttp.open("POST", phpcheck, true);      // set the request to php file

      // adds  a header to tell the PHP script to recognize the data as is sent via POST
      xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlHttp.send(datatosend);     // calls the send() method with datas as parameter

      // Check request status
      xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) setelm(elm, xmlHttp.responseText);
    else if(elm.value =='') setelm(elm, 'This field must be completed.');

  // register onchange event to form elements that must be validated with PHP via Ajax
  for(var i=0; i<fields.length; i++) {
    if(document.getElementById(fields[i])) {
      var elm = document.getElementById(fields[i]);
      err[elm.name] = 0;  //store fields-name in $err with value 0 (not checked)
      elm.addEventListener('change', function(e){ checkAjax(e.target);});

/* USAGE */
// array with IDs of the fields to validate
var fields = ['exname', 'expass', 'exmail'];

// create an object instance of checkFormElm(), passing the ID of the submit button, and the $fields
var chkF = new checkFormElm('exsbm', fields);

• In this example, the PHP script that checks and validates the form field value is added in "check.php" file.
Here is a php code that validate the Name, Password, and E-mail. You can create the PHP script to check the input field value according to your needs, with data stored on your server. The PHP response must be an empty string when the value is valid.
// https://coursesweb.net/php-mysql/

// array with error messages for each input field
$err = array(
  'exname'=>'Not registered name.',
  'expass'=>'Incorrect password.',
  'exmail'=>'Invalid email address.'
$reout = '';         // data to return

// Valided values for name, password, email
$name = 'coursesweb';
$password = 'mypass';
$email = 'me@domain.com';

// validate the POST values
if(isset($_POST['exname']) && $_POST['exname'] != $name) $reout = $err['exname'];
else if(isset($_POST['expass']) && $_POST['expass'] != $password) $reout = $err['expass'];
else if(isset($_POST['exmail']) && $_POST['exmail'] != $email) $reout = $err['exmail'];

echo $reout;

• Now we set CSS code to style the error message, and the input fields for when they are invalid, and validated:
/* style for validated field */
.vinp {
 background: #efeffe;
 border: 1px solid blue;

/* style for invalided field */
.errinp {
 background: #fefbda;
 border: 2px dashed red;

/* style for error message */
.err {
 margin: 0 5px;
 color: red;
 font-style: italic;

Daily Test with Code Example

Which attribute is used in <img> tag for the address of the image?
href src rel
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;
#id {
  display: none;
What instruction stops the execution of a while() or for() statement?
continue prompt() break
for(var i = 0; i< 8; i++) {
  if(i > 1) break;
Indicate the function that can create a constant.
define() include() defined()
define("CONSTANT_NAME", "value");
Check and Validate input field when loses focus, with PHP via Ajax

Last accessed pages

  1. PHP Script Website Mini-Traffic (6886)
  2. Send POST data with file_get_contents (2839)
  3. PHP Unzipper - Extract Zip, Rar Archives (30710)
  4. Node.js Move and Copy file (27850)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (135114)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (445)
  2. SHA1 Encrypt data in JavaScript (236)
  3. PHP Unzipper - Extract Zip, Rar Archives (218)
  4. Read Excel file data in PHP - PhpExcelReader (217)
  5. Get and Modify content of an Iframe (139)