You can understand this requirement can be easily done by using one web form and submitting the data to a server side script. But by using Ajax we need not submit the form and load a new page. The same page can collect the information at the background using XMLHttpRequest and get the data for us. This is a better way of doing the same thing with improved user experience.
Here is the demo. Please use customer id 1, 2 or 3 to get the name of the customer for any other id you will get message saying No customer name available. XMLHttpRequest for Ajax please read this.
Usually the data is taken from a customer table but for simplicity we have kept an array here with three customer details. This server side part can be extended to connect a database and details of customer can be collected. This part of the code we kept in a PHP script ( code.php file ) and you can easily modify this small script. The small PHP code is here.
As you can see in the above code, the script collects the customer_id and then if the id is present inside the (PHP) array then the name of the corresponding customer is returned, otherwise a message saying customer name not there is returned to calling html page. We used array_key_exists() to search for the customer id.
Inside the function stateChanged() we can collect the response we get from the server side php script and assign that received data to one div tag identified by txtHint. The data is displayed as it is received from the server, note that there is no need of page reload.
Here is the total code of html page. You can download the full code of both the files at the end of this page.
Download the zip file ( both code.htm & code.php )
This article is written by plus2net.com team.
|▼ Click for more tutorial on Ajax & PHP|