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:

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. Validating form using Ajax

  • Now, it is time to include jQuery and its functionality:
  • We will also initialize the document ready function:
  • 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:

    $value){ $row = "

  • ".str_replace($string, "".$string."", $value)."
  • "; $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. Dynamic Dropdown

    • When the HTML is ready, we will play with CSS:

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

    • When everything is set, we will call the ajaxDropdownInit function within the document ready function:
    • $(document).ready(function(){




      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.

      '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": "
    • Milan

    • Milan2

    • Milan3

    • " }]

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

      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.

      Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.


      Please enter your comment!
      Please enter your name here