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" />
</form>
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

<script>
// 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;
          break;
        }
      }

      // if not invalid element, enables the submit button, and sends the form
      if(inv == 0 && elm_sbm) {
        elm_sbm.removeAttribute('disabled');
        elm_sbm.form.submit();
      }
    }
  }

  // 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);
</script>

• 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.
<?php
// 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

HTML
CSS
JavaScript
PHP-MySQL
Which HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Check and Validate input field when loses focus, with PHP via Ajax

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142308)
  2. Get and Modify content of an Iframe (32367)
  3. $_GET, $_POST and $_REQUEST Variables (33884)
  4. Ajax-PHP Chat Script (49508)
  5. JavaScript Course - Free lessons (31647)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (311)
  2. The Mastery of Love (48)
  3. CSS cursor property - Custom Cursors (36)
  4. Read Excel file data in PHP - PhpExcelReader (35)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (31)