Building interactive web apps using AJAX with PHP
This article was last updated on 2009-12-18 21:17:43
Using javascript in web pages to get data from a server has traditionally had the drawback of having to reload your page each time you make a request; submitting a form, waiting for a response and re-loading your original page with the results. 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>
<head>
<title>Clear Forward - Ajax Credit Card Example</title>
<script src="cardfees.js"></script>
</head>
<body>
<form name="form1" id="form1">
<strong>Please select your credit card:</strong>
<br/>
<select name="credit_card_types" id="credit_card_types" onChange="checkCardFees();">
<option value="-" selected="selected">--please choose--</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="Amex">American Express</option>
</select>
</form>
<strong>Original Amount:</strong>
<br/>
<span id="original_price">10.00</span>
<br/><br/>
<strong>Card Fee:</strong>
<br/>
<span id="card_fees">
No fee applied.
<br/><br/>
<strong>Total Amount:</strong>
<br/>
10.00
</span>
</body>
</html>
Fig. 1 ajax-credit-card-example.php
var xmlHttp
function checkCardFees(){
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var type = getCardSelected();
var price = getOriginalPrice();
var url="http://www.clearforward.com/cardfees.php"
url=url+"?type="+type+"&price="+price
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("card_fees").innerHTML=xmlHttp.responseText
}
}
function getOriginalPrice() {
var original_price = document.getElementById("original_price").innerHTML;
return original_price;
}
function getCardSelected() {
var selected_card;
for (var i=0; i
selected_card = document.form1.credit_card_types[i].value;
}
}
return selected_card;
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Fig. 2 cardfees.js
$type = $_GET['type'];
$price = (float)$_GET['price'];
$response = "";
if ($type == "Visa") {
//charge a card handling fee of 1.00 for Visa
$card_charge = number_format(1.00, 2);
$total_amount = number_format(($price + $card_charge), 2);
$response .= $card_charge . "<br/><br/><strong>Total Amount:</strong><br/>" . $total_amount;
}
else if ($type == "Mastercard") {
//charge a card handling fee of 2.00 for Mastercard
$card_charge = number_format(2.00, 2);
$total_amount = number_format(($price + $card_charge), 2);
$response .= $card_charge . "<br/><br/><strong>Total Amount:</strong><br/>" . $total_amount;
}
else if ($type == "Amex") {
//charge a card handling fee of 3.00 for Amex
$card_charge = number_format(3.00, 2);
$total_amount = number_format(($price + $card_charge), 2);
$response .= $card_charge . "<br/><br/><strong>Total Amount:</strong><br/>" . $total_amount;
}
else {
//put exception handling code here
$response .= "Please select a card.";
}
echo $response;
Fig. 3 cardfees.php
Click here for the working example.
Need a web solution built for you? Whatever your online needs, contact Clear Forward at to find out how we can deliver the internet for your benefit.

