Contents |
The XMLHttp API's were first written by Microsoft and may available in Internet Explorer 5.0. It was made available as an ActiveX object. Mozilla later implemented the API into Mozilla 1.0. This was quickly followed by all other major browsers including Safari 1.2 and Opera 8.0.
The XMLHttp API's allow a browser to make a request to a server without loading an entirely new page. This allows for a very dynamic web experience. As users interact with a web page by clicking or typing, the page can react and change.
The interface into the XMLHttpRequest object if fairly simple. There are only a few basic things you need to know to get started. The remainder of this article will walk you through a simple example of how to use the XMLHttpRequest object.
The first step is to create a valid script area in your HTML file. You can put this in the HEAD or the BODY of your page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules</title>
<script type="text/javascript">
//script goes here
</script>
</head>
</body>
</body>
</html>
The next step is to create a javascript function. Then within the function we want to create a new XMLHttpRequest object. The XMLHttpRequest object is built into all browsers except IE, where you have to retrieve an ActiveX object.
<script type="text/javascript">
//script goes here
function makeRequest(){
client = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
}
</script>
Next we need to set up the object and make the request.
function makeRequest(){
client = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
client.onreadystatechange = callback;
client.open("get","index.php",true);
client.send(null);
}
The first new line of code adds a callback routine to the object. Every time the ready state of the request changes this callback function will be run. The ready state is basically what state the request is in. The request will change between the following states:
This will be important when we actually write the callback because we will normally want to wait until the request is in the 'Complete' state before we do anything with it.
The second new line of code sets up a connection with the server. The first parameter is the method for accessing the server, usually get or post. The second parameter is the URL that is going to be accessed. The URL can contain a query string. For example, index.php?name1=param1&name2=param2. The third parameter sets the connection to either synchronous or asynchronous mode. A value of true will set the connection to be asynchronous and false will set the connection to be synchronous. A synchronous connection will block all browser activity until the request returns. Be very careful if you do this as the user will not be able to do anything while the browser waits. Generally you will want an asynchronous connection and a callback to deal with the request.
The third new line of code allows you to send data in the body of the HTTP request. This is where you would send any post data if you were using the post method. For example, client.send("name1=param1&name2=param2");. One more note about sending post data. Before sending the data you must set the appropriate HTTP header value to alert the server that the data is URL encoded post data. You can do this by calling the setRequestHeader method on the client before calling the send method. For example: client.setRequestHeader('Content-Type','application/x-www-form-urlencoded');.
There is one more thing we should add to this code to make it a little more robust.
function makeRequest(){
try{
client = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
client.onreadystatechange = callback;
client.open("get","index.php",true);
client.send(null);
} catch (e) {
alert("You need a newer browser");
}
}
The added try block will help to gracefully catch the problem of a user having an older browser that does not have a XMLHttpRequest object available to it. Now, I would not suggest just alerting the user that their browser is too old. You should do something that lets your page still display correctly, but this all depends on your specific needs and audience.
New it is time to write the callback function.
function callback(){
if (client.readyState == 4) {
if (client.status == 200) {
alert("Response Success:\n" + client.responseText);
} else {
alert("Response Error:\n" + client.statusText);
}
}
}
The first if statement references the ready state of the request. If the ready state is 4, which means the request has completed, then we are going to look further at the request. The second if statement checks the status of the request. The value here is the HTTP response code returned by the server. A value of 200 means the request was successful. Based on these two critera you can perform what ever task you need to based on the data that was returned.
What the server returns to a XMLHttpReqest objects request is an HTTP response. You can use any part of the response on the client side, including the HTTP headers. Perhaps the most useful bit of data though is the body of the response. The entire body of the HTTP response can be found in the object's statusText property. You can see this used in the examples above.
The data sent to the client can be in any form. Some of the more useful forms include plain text, XML or JSON. Any of these forms may be useful depending on what you are trying to accomplish. The simple sample below uses JSON.
The following is a very simple application that changes the text of a button based on the random message returned to the page from the server. To test this application, copy all of the text below into an editor and save it as a php file. Put the php file in your php enabled server area and hit the page. If you would like to translate this simple sample into another language, please do.
<?php
if(isset($_GET['run'])){
$messages = array('Hello World!', 'You pushed my button', 'You recieved message three');
echo "document.getElementById('mybutton').value='".$messages[rand(0,2)]."'";
exit();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules</title>
<script type="text/javascript">
function makeRequest(){
try{
client = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
client.onreadystatechange = callback;
client.open("get","index.php?run",true);
client.send(null);
} catch (e) {
alert("You need a newer browser");
}
}
function callback(){
if (client.readyState == 4) {
if (client.status == 200) {
eval(client.responseText);
} else {
alert("Response Error:\n" + client.statusText);
}
}
}
</script>
</head>
</body>
<input type="button" id="mybutton" name="mybutton" value="Click Me" onclick="makeRequest()" />
</body>
</html>
Making your web application AJAX enabled is not as hard as it may seem. If you could follow the code above you have a good start. You will also need to understand how to manipulate the HTML DOM, as well as how to harness the JavaScript event system. If you understand these three things you can do most anything!
© 2008 Novell, Inc. All Rights Reserved.