Basic AJAX tutorial
Ever wondered how to make your website perform an AJAX-request? Keep reading, and find out. Or, if you're a seasoned pro needing no explanation, just the code, visit the example and view the source. You can always come back for the explanation.The example accompanying this tutorial will encrypt a visitor's comments, server-side, without reloading the client-side webpage. The beauty of doing encryption on the server side is that the actual commands used for the encryption are hidden for the user. They can see what's going IN, what's coming OUT, but not what's happening in between, which makes reverse-engineering the encrypted text a lot more difficult. Let's get started.
As we said, we want to encrypt a visitor's comments. So, let's create a form where those comments can be entered. This is basic HTML:
Why the "return false"? Simple. I don't want the form to actually be submitted. You'll notice I've told the button to perform a specific action when it's clicked. (onclick="encrypt(); return false"). When the button is clicked, I want it to run the JavaScript function "encrypt" with no arguments, and then stop, without performing its default action (submitting the form).
The "encrypt" function prepares an XMLHTTP object (which is what actually performs the AJAX-request) and uses it to retrieve the encrypted comments. To get the XMLHTTP object, it uses another function, called "createAjaxObject". Here's the full code for both functions, explained in detail below:
-
<script type="text/javascript">
-
function encrypt()
-
{
-
var oAjax = createAjaxObject();
-
if (!oAjax)
-
{
-
alert('Unable to create an XMLHTTP-object. Your comments will not be encrypted.');
-
return;
-
}
-
-
var sUrl = "ajax_response.php?comment=";
-
var sComment = document.getElementById('comments').value;
-
sUrl += escape(sComment);
-
-
oAjax.open("GET", sUrl, true);
-
oAjax.send(null);
-
-
oAjax.onreadystatechange = function()
-
{
-
if (oAjax.readyState == 4 && oAjax.status == 200)
-
{
-
document.getElementById('encrypted').innerHTML = oAjax.responseText;
-
}
-
}
-
}
-
-
function createAjaxObject()
-
{
-
var oAjax = false;
-
-
if (window.XMLHttpRequest)
-
{
-
oAjax = new XMLHttpRequest();
-
}
-
else
-
{
-
if (window.ActiveXObject) {
-
var aXmlHttpVersions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
-
"Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
-
"Microsoft.XMLHTTP"];
-
-
for (var i = 0; i <aXmlHttpVersions.length; i++)
-
{
-
try
-
{
-
oAjax = new ActiveXObject(aXmlHttpVersions[i]);
-
-
if (oAjax) break;
-
}
-
catch (objException)
-
{
-
}
-
}
-
}
-
}
-
-
return oAjax;
-
}
-
</script>
Let's examine this code and see what it does. We'll start with the "createAjaxObject" function, because that's the first thing that gets called.
-
var oAjax = false;
First create a variable oAjax, and set it to false. If all methods to create an XMLHTTP object fail (we'll come to that next), this variable won't be altered.
-
if (window.XMLHttpRequest)
-
{
-
oAjax = new XMLHttpRequest();
-
}
If the default method for creating an XMLHTTP object is available, use that. This will work in most browser, including Mozilla, Netscape, Firefox, Safari, Opera and Internet Explorer 7. For the benefit of older versions of Internet Explorer, we'll need another method, which makes use of ActiveX. We'll need to check if ActiveX is available, first.
-
else
-
{
-
if (window.ActiveXObject) {
-
var aXmlHttpVersions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
-
"Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
-
"Microsoft.XMLHTTP"];
If it's possible to create an ActiveXObject, create an array of Microsoft's proprietary ActiveX XMLHTTP objects. I'm doing this for a very specific reason. Msxml2.XMLHTTP.7.0 is the most recent version I know of that can be used for creating an XMLHTTP object. Microsoft.XMLHTTP is the oldest. As with most pieces of software, newer versions mean better functionality.
We're going to try to create an XMLHTTP object using the most recent version available in the user's browser. To do that, we have to iterate through the array using a for-loop. We'll try to create an ActiveX object with the current iteration from the aXmlHttpVersions array, and break out of the loop if an object was succesfully created. If all failed, the loop will end of its own accord.
-
for (var i = 0; i <aXmlHttpVersions.length; i++)
-
{
-
try
-
{
-
oAjax = new ActiveXObject(aXmlHttpVersions[i]);
-
-
if (oAjax) break;
-
}
-
catch (objException)
-
{
-
}
-
}
The "if (oAjax) break;" makes sure that we stop iterating the array. If there is a problem with one (or more) of the XMLHTTP objects, they might cause an object exception. These tend to be alerted to the user, at the very least with a yellow triangle in the lower left corner of the browser window. Unless we catch them and don't do anything with them. That's what the empty "catch (objException)" function is for.
At the very end of the function, we return the oAjax variable. If an XMLHTTP object was created, either using XMLHttpRequest or one of Microsoft's ActiveX objects, this variable will contain that object. If both failed, the variable will still be false, because that's what we set it to when we created it.
Now we can have a look at the "encrypt" function, and what we have to do with the now created XMLHTTP object to send a request and get a response.
-
var oAjax = createAjaxObject();
-
if (!oAjax)
-
{
-
alert('Unable to create an XMLHTTP-object. Your comments will not be encrypted.');
-
return;
-
}
First, use the createAjaxObject function to create an XMLHTTP object. If that fails (or, the function returns false) alert a message saying the object could not be created, and exit the function.
-
var sUrl = "ajax_response.php?comment=";
-
var sComment = document.getElementById('comments').value;
-
sUrl += escape(sComment);
We need to have a URL to send the request to. For this example, I've created a file called ajax_response.php, which requires a paramater called "comment". This comment is the value that is to be encrypted. We need to get that from the textarea, which has the ID "comments". Since this comment can have all sorts of weird characters in it, we need to escape it to make it safe to append to the url. We do this escaping while we're adding it to the url.
-
oAjax.open("GET", sUrl, true);
-
oAjax.send(null);
Here, we first open a new connection, where we use a GET-request on the url. The "true" in there means the request is flagged as "asynchronous" (the first A in AJAX). This is part of the HTTP protocol, so we could also use a POST request. The main difference between the two is that a GET request has all the variables in the url itself, where a POST request has all the variables in the body of the request. Because this is a GET request, we do not have to send a body with it, and we send a null value. Were it a POST request, our url would be "ajax_response.php" and our oAjax.send would have "comments=(the escaped comments string)" instead of "null".
-
oAjax.onreadystatechange = function()
-
{
-
if (oAjax.readyState == 4 && oAjax.status == 200)
-
{
-
document.getElementById('encrypted').innerHTML = oAjax.responseText;
-
}
-
}
The XMLHTTP object has a built-in function called onreadystatechange. This is fired every time the state of the XMLHTTP object changes. Here, we tell it what to do when the function is called.
If the object's readyState equals 4 ("complete"), and its status equals 200 ("OK"), that means that the loading of the response is complete. If it is, update the element with ID "encrypted" and set its contents to the XMLHTTP object's responseText. The responseText is the value we received back from the server-side script.
For more information about the XMLHttpRequest object, I recommend you visit the Apple Developer Connection website at http://developer.apple.com/internet/webcontent/xmlhttpreq.html.
Now then, we've seen the entire client-side script. But what happens on the server side? Well, in my case it's PHP.
-
<?php
-
-
-
?>
You can do whatever you want server-side, just make sure that you put whatever you want to return to the originating page (where the XMLHTTP object uses a responseText value) in the page's output. What that means, is that when you enter the url (assuming you're using a GET request) manually in the address bar, you should see the exact output you want to send back to the originating page.
You can see this tutorial's example in action right here.
