8 min read

(For more resources on PHP Ajax, see here.)

Validating a form using Ajax

The main idea of Ajax is to get data from the server in real time without reloading the whole page. In this task we will build a simple form with validation using Ajax.

Getting ready

As a JavaScript library is used in this task, we will choose jQuery. We will download (if we haven’t done it already) and include it in our page. We need to prepare some dummy PHP code to retrieve the validation results. In this example, let’s name it inputValidation.php. We are just checking for the existence of a param variable. If this variable is introduced in the GET request, we confirm the validation and send an OK status back to the page:

<?php $result = array(); if(isset($_GET["param"])){ $result["status"] = "OK"; $result["message"] = "Input is valid!"; } else { $result["status"] = "ERROR"; $result["message"] = "Input IS NOT valid!"; } echo json_encode($result); ?>

How to do it…

  1. Let`s start with basic HTML structure. We will define a form with three input boxes and one text area. Of course, it is placed in :
  2. <body> <h1>Validating form using Ajax</h1> <form class="simpleValidation"> <div class="fieldRow"> <label>Title *</label> <input type="text" id="title" name="title" class="required" /> </div> <div class="fieldRow"> <label>Url</label> <input type="text" id="url" name="url" value="http://" /> </div> <div class="fieldRow"> <label>Labels</label> <input type="text" id="labels" name="labels" /> </div> <div class="fieldRow"> <label>Text *</label> <textarea id="textarea" class="required"></textarea> </div> <div class="fieldRow"> <input type="submit" id="formSubmitter" value="Submit" disabled= "disabled" /> </div> </form> </body> <style>

  3. For visual confirmation of the valid input, we will define CSS styles:
  4. label{ width:70px; float:left; } form{ width:320px; } input, textarea{ width:200px; border:1px solid black; float:right; padding:5px; } input[type=submit] { cursor:pointer; background-color:green; color:#FFF; } input[disabled=disabled], input[disabled] { background-color:#d1d1d1; } fieldRow { margin:10px 10px; overflow:hidden; } failed { border: 1px solid red; } </style>

  5. Now, it is time to include jQuery and its functionality:
  6. <script src="js/jquery-1.4.4.js"></script> <script> var ajaxValidation = function(object){ var $this = $(object); var param= $this.attr('name'); var value = $this.val(); $.get("ajax/inputValidation.php", {'param':param, 'value':value }, function(data) { if(data.status=="OK") validateRequiredInputs(); else $this.addClass('failed'); },"json"); } var validateRequiredInputs = function (){ var numberOfMissingInputs = 0; $('.required').each(function(index){ var $item = $(this); var itemValue = $item.val(); if(itemValue.length) { $item.removeClass('failed'); } else { $item.addClass('failed'); numberOfMissingInputs++; } }); var $submitButton = $('#formSubmitter'); if(numberOfMissingInputs > 0){ $submitButton.attr("disabled", true); } else { $submitButton.removeAttr('disabled'); } } </script>

  7. We will also initialize the document ready function:
  8. <script> $(document).ready(function(){ var timerId = 0; $('.required').keyup(function() { clearTimeout (timerId); timerId = setTimeout(function(){ ajaxValidation($(this)); }, 200); }); }); </script>

  9. When everything is ready, our result is as follows:

How it works…

We created a simple form with three input boxes and one text area. Objects with class required are automatically validated after the keyup event and calling the ajaxValidation function. Our keyup functionality also includes theTimeoutfunction to prevent unnecessary calls if the user is still writing. The validation is based on two steps:

  • Validation of the actual input box: We are passing the inserted text to the ajax/inputValidation.php via Ajax. If the response from the server is not OK we will mark this input box as failed. If the response is OK, we proceed to the second step.
  • Checking the other required fields in our form. When there is no failed input box left in the form, we will enable the submit button.

There’s more…

Validation in this example is really basic. We were just checking if the response status from the server is OK. We will probably never meet a validation of the required field like we have here. In this case,it’s better to use the length property directly on the client side instead of bothering the server with a lot of requests,simply to check if the required field is empty or filled. This task was just a demonstration of the basic Validationmethod. It would be nice to extend it with regular expressions on the server-side to directly check whether the URL form or the title already exist in our database, and let the user know what the problem is and how he/she can fix it.

Creating an autosuggest control

This recipe will show us how to create an autosuggest control. This functionality is very useful when we need to search within huge amounts of data. The basic functionality is to display the list of suggested data based on text in the input box.

Getting ready

We can start with the dummy PHP page which will serve as a data source. When we call this script with GET method and variable string, this script will return the list of records (names) which include the selected string:

<?php $string = $_GET["string"]; $arr = array( "Adam", "Eva", "Milan", "Rajesh", "Roshan", // ... "Michael", "Romeo" ); function filter($var){ global $string; if(!empty($string)) return strstr($var,$string); } $filteredArray = array_filter($arr, "filter"); $result = ""; foreach ($filteredArray as $key => $value){ $row = "<li>".str_replace($string, "<strong>".$string."</strong>", $value)."</li>"; $result .= $row; } echo $result; ?>

How to do it…

  1. As always, we will start with HTML. We will define the form with one input box and an unsorted list datalistPlaceHolder:
  2. <h1>Dynamic Dropdown</h1> <form class="simpleValidation"> <div class="fieldRow"> <label>Skype name:</label> <div class="ajaxDropdownPlaceHolder"> <input type="text" id="name" name="name" class="ajaxDropdown" autocomplete="OFF" /> <ul class="datalistPlaceHolder"></ul> </div> </div> </form>

  3. When the HTML is ready, we will play with CSS:
  4. <style>
    label { width:80px; float:left; padding:4px; }
    form{ width:320px; }
    input, textarea{ 
    width:200px; border:1px solid black;
    
    border-radius: 5px; float:right; padding:5px;
    }
    
    input[type=submit] { cursor:pointer; 
    background-color:green; color:#FFF; }
    
    input[disabled=disabled] { background-color:#d1d1d1; }
    
    fieldRow { margin:10px 10px; overflow:hidden; }
    validationFailed { border: 1px solid red; }
    validationPassed { border: 1px solid green; }
    
    .datalistPlaceHolder {
    width:200px; border:1px solid black;
    border-radius: 5px;
    float:right; padding:5px; display:none;
    }
    
    ul.datalistPlaceHolder li { list-style: none; 
    cursor:pointer; padding:4px; }
    
    ul.datalistPlaceHolder li:hover { color:#FFF; 
    background-color:#000; }
    </style>
    

     

    Now the real fun begins. We will include jQuery library and define our keyup events:

    <script src="js/jquery-1.4.4.js"></script> <script> var timerId; var ajaxDropdownInit = function(){ $('.ajaxDropdown').keyup(function() { var string = $(this).val(); clearTimeout (timerId); timerId = setTimeout(function(){ $.get("ajax/dropDownList.php", {'string':string}, function(data) { if(data) $('.datalistPlaceHolder').show().html(data); else $('.datalistPlaceHolder').hide(); }); }, 500 ); }); } </script>

  5. When everything is set, we will call the ajaxDropdownInit function within the document ready function:
  6. <script>

    $(document).ready(function(){

    ajaxDropdownInit();

    });

    </script>

     

    Our autosuggest control is ready. The following screenshot shows the output:

How it works…

The autosuggest control in this recipe is based on the input box and the list of items in datalistPlaceHolder. After each keyup event of the input box,datalistPlaceHolder will load the list of items from ajax/dropDownList.php via the Ajax function defined in ajaxDropdownInit. A good feature of this recipe is thetimerID variable that,when used with thesetTimeout method, will allow us to send the request on the server only when we stop typing (in our case it is 500 milliseconds). It may not look so important, but it will save a lot of resources. We do not want to wait for the response of “M” typed in the input box, when we have already typed in “Milan”. Instead of 5 requests (150 milliseconds each), we have just one. Multiply it, for example, with 10,000 users per day and the effect is huge.

There’s more…

We always need to remember that the response from the server is in the JSON format.

[{ 'id':'1', 'contactName':'Milan' },...,{ 'id':'99', 'contactName':'Milan (office)' }] Using JSON objects in JavaScript is not always useful from the performance point of view. Let's imagine we have 5000 contacts in one JSON file. It may take a while to build HTML from 5000 objects but, if we build a JSON object, the code will be as follows: [{ "status": "100", "responseMessage": "Everything is ok! :)", "data": "<li><h2><ahref="#1">Milan</h2></li> <li><h2><ahref="#2">Milan2</h2></li> <li><h2><ahref="#3">Milan3</h2></li>" }]

It may take a while to build HTML from 5000 objects but, if we build a JSON object, the code will be as follows:

<?php echo "STEP 1"; // Same for 2 and 3 ?>

In this case, we will have the complete data in HTML and there is no need to create any logic to create a simple list of items.

LEAVE A REPLY

Please enter your comment!
Please enter your name here