Building interactive web apps using AJAX with PHP
|
This tutorial will illustrate how AJAX (Asynchronous JavaScript and XML) provides an advantage over this approach through the ability to interact with the server without reloading the page, resulting in faster, more responsive web apps. By Joe Barber |
AJAX is based upon existing technology, javascript and HTTP requests, the cornerstone of which is the is the XMLHttpRequest object used by most modern browsers. This is used to handle HTTP requests between a web browser and the server; through this object, data transfer is asynchronous so once the response from the server is complete, the page can be updated without reloading a page.
To illustrate this technique, below is a fully worked example of using AJAX to dynamically update a page without reloading it. In this example taken from a typical website shopping basket, a company may charge a fee for using a credit card online, and may charge different fees depending on the type of card used. Depending on which card a customer might select from a dropdown box, it would be useful to update the fee they will be charged and the updated total price as they select it so they can see how much they will be charged straight away.
The example consists of three separate files; Fig. 1 shows ajax-credit-card-example.php, the basic web page with the form element. Fig. 2 shows cardfees.js, the javascript file that uses the XMLHttpRequest object to call the server (Fig. 3, cardfees.php) to echo back a response depending on the credit card type that the user selected on the web page. The stateChanged() method in the javascript shows that when a complete response has been received from the server’s cardfees.php (readyState = 4), then update the span element ‘card_fees’ in the web page with the response from the server.
Using AJAX, once a connection to the server has been established, it would be easy to extend this example to have cardfees.php bringing back results from a database.
Click here for the working example
|
<html> <script src=”cardfees.js”></script> <body> <form name=”form1″ id=”form1″> <select name=”credit_card_types” id=”credit_card_types” onChange=”checkCardFees();”> <strong>Original Amount:</strong> <span id=”original_price”>10.00</span> <br/><br/> <strong>Card Fee:</strong> <span id=”card_fees”> <strong>Total Amount:</strong> </body> Fig. 1 ajax-credit-card-example.php |
|
var xmlHttp function checkCardFees(){ xmlHttp=GetXmlHttpObject() var type = getCardSelected(); var url=”http://dev.clearforward.com/cardfees.php” function stateChanged(){ function getOriginalPrice() { function getCardSelected() { for (var i=0; i return selected_card; function GetXmlHttpObject(){ Fig. 2 cardfees.js |
|
$type = $_GET['type']; $response = “”; if ($type == “Visa”) { else if ($type == “Mastercard”) { else if ($type == “Amex”) { else { echo $response; Fig. 3 cardfees.php |

No comments yet.