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...
Let's start with basic HTML structure. We will define a form with three input boxes...