AJAX - The Complete Reference
With the basic concepts out of the way, like any good programming book we now jump right into coding with the ubiquitous “Hello World” example. In this version of the classic example, we will press a button and trigger an asynchronous communication request using an XMLHttpRequest (XHR) object and the Web server will issue an XML response which will be parsed and displayed in the page. The whole process is overviewed in Figure 1-4.
To trigger the action, a simple form button is used which, when clicked, calls a custom JavaScript function sendRequest() that will start the asynchronous communication. It might be tempting to just bind in a JavaScript call into an event handler attribute like so:
<form action="#">
<input type="button" value="Say Hello" onclick="sendRequest();" />
</form>
However, it is a much better idea to simply use name or id attributes for the form fields or other tags that trigger activity:
<form action="#">
<input type="button" value="Say Hello" id="helloButton" />
</form>
and then bind the onclick event using JavaScript like so:
window.onload = function ()
{
document.getElementById("helloButton").onclick = sendRequest;
};
A <div> tag named responseOutput is also defined. It will eventually be populated with the response back from the server by reference via DOM method, such as getElementById().
<div id="responseOutput"> </div>
When the sendRequest function is invoked by the user click, it will first try to instantiate an XMLHttpRequest object to perform the communication by invoking another custom function createXHR, which attempts to hide version and cross-browser concerns. The function uses try-catch blocks to attempt to create an XHR object. It first tries to create it natively as supported in Internet Explorer 7.x, Safari, Opera, and Firefox. Then, if that fails, it tries using the ActiveXObject approach supported in the 5.x and 6.x versions of Internet Explorer.
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
function sendRequest()
{
var xhr = createXHR(); // cross browser XHR creation
if (xhr)
{
// use XHR
}
}
If the createXHR function returns an XHR object, you begin your server communication by using the open() method to create an HTTP GET request to the URL http://ajaxref.com/ch1/sayhello.php. A true flag is specified to indicate that the request should proceed
asynchronously.
xhr.open("GET","http://ajaxref.com/ch1/sayhello.php",true);
onreadystatechange = function(){handleResponse(xhr);};
Closures might be unfamiliar to those readers newer to JavaScript, but they are fully covered in Chapter 3 as well as Appendix A.
Finally, the request is sent on its way using the send() method of the previously created XHR object. The complete sendRequest function is shown here:
function sendRequest()
{
var xhr = createXHR(); // cross browser XHR creation
if (xhr) // if created run request
{
xhr.open("GET","http://ajaxref.com/ch1/sayhello.php",true);
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
}
Eventually, the server should receive the request and invoke the simple sayhello.php program shown here.
<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/xml");
$ip = $_SERVER['REMOTE_ADDR'];
$msg = "Hello World to user from " . $ip . " at ". date("h:i:s A");
print "<?xml version='1.0' encoding='UTF-8'?>";
print "<message>$msg</message>";
?>
Ajax does not favor or require any particular server-side language or framework. The general idea should be the same in whatever environment you are comfortable. For example, sayhello.jsp looks quite similar to the PHP version.
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setContentType("text/xml");
String ip = request.getRemoteAddr();
String msg = "Hello World to user from " + ip + " at " + new java.text
.SimpleDateFormat("h:m:s a").format(new java.util.Date());
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.print("<response>" + msg + "</response>");
%>
NOTE PHP is used in most examples, given its simplicity and readability, but any server-side technology, such as Ruby, ASP.NET, and Java, is more than capable of servicing Ajax requests.
|