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.
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 )
Be the first to post comment on this article :
Ajax & PHP scripts Creating XMLHttp object in different browsers Sample Code: Get Method of Ajax form submission Server Clock:: Display real-time date and time of server Dependant drop down list box using Ajax & PHP Email validation using Ajax in a form Getting customer details by entering customer id using Ajax Progress Bar using Ajax Progress Bar using MySQL PHP & Ajax Displaying Message at client side using Ajax & PHP Web page HTML form validation using Ajax and PHP Form validation with onBlur event using Ajax and PHP
Json support in PHP json_encode to generate Json string from PHP Array data Json Data formatting to return database records to main script Searching MySql database as we type using Ajax Displaying all records based on selection of a drop down list box