When you go to google and start typing in a query, you get a dropdown list of what google thinks you might be typing. If you're not aware, the way they do that is by using Ajax, a way of transferring data between the server and your browser without sending the entire page back in forth. By sending smaller packages, it gives the illusion of seamless data transfer. It's like having your own personal google right in your browser. So, today I set out to demystify the creature known as Ajax!
My search started at
W3C Schools, where else? Their
Ajax tutorial is of course top notch - I'll summarize it in my own words though.
The driver behind Ajax is Javascript. Javascript creates the object (XMLHttpRequest) that talks back and forth with the server. Javascript passes it any variables. Javascript sets the return string into an appropriate container. W3C Schools break down (rightly so) the javascript functions you will need to get your Ajax-enabled page up and running:
Someone set us up the bomb XMLHttpRequest object
<script>
var xmlhttp
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
The above code will declare a variable to hold the XMLHttpRequest object. Important to note is that it's outside the declaration of the function. Making it global allows it to be accessible from multiple functions. After that, the function to instantiate the XMLHttpRequest object is pretty straightforward. It needs to be set up one way for older IE browsers, and another way for more modern browsers.
Ok we have a function to set up the XMLHttpRequest object, now you need a function to actually make the Ajax call!
Fetch!function ajaxFunction(parameterValue)
{
//Set up the XMLHttpObject
xmlhttp = GetXmlHttpObject();
//Set the object's state change event to run our handler
//We will define the 'stateChanged' function in just a second
xmlhttp.onreadystatechange=stateChanged;
//Set up the URL
var url = "serverJob.aspx"
url = url + "?parameter=" + parameterValue
//Send the XMLHttpObject off to the server
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
Ok, a few important things to note here. The way we are going to pass parameters to the server is in the QueryString. As you can see, we set up a URL that has a parameter and a parameter value in the familiar way you might pass form data in standard HTML. The open() command takes 3 parameters: the method to use (GET or POST), the url we want to do the work, and a boolean signifying whether or not we want it to run asynchronously (I can't see a time where we wouldn't, but hey). Then we send it off on it's merry way, and continue doing whatever it was we were doing. The event handler should handle the rest:
The function 'stateChanged' will take care of the data as it comes back from the server.
Yeah yeah I gots ya stinkin data, now whatcha wants me ta do wit it?function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("yourOutputControl").innerHTML=xmlhttp.responseText;
}
}
This convenient table from W3C Schools should pretty much sum up what's going on here
We want to wait for the state to be equal to 4 (completed), and the data to be back from the server. Once it is, we set the response text to a control. That's what's going on inside the if-statement. Get a reference to your control and set the value.
That's pretty much it! We create an XMLHttpRequest object, we send it a QueryString, and it sends us a result string in return. That's an important point.
The only exchanges are parameter strings and a single return string. Ok, one final piece of the puzzle remains. What's going on inside serverJob.aspx? Quite simply, it's a standard ASPX page that returns a single string:
<%
Response.Expires = -1
dim m as myObject
dim returnString as string = m.doSomeWork(Request.QueryString("parameter"))
Response.Write(returnString)
%>
"Response.Expires = -1" means that we won't cache this aspx page, ever, since we want it to run "fresh" every time we request it. After that, you are free to declare instantiations of your objects, make database calls, and code to your heart's desire. In the above example, I've declared an object of type myObject and had it do some work based on the parameter that was passed in on the QueryString. Pretty simple! Again, the important thing to note here is there is one string that is returned, and instead of using the "return" keyword, we use Response.Write.
So there it is, your first introduction to Ajax! I can't believe it's taken me this long to get into it, when it really is so simple. I'd love to hear your Ajax adventures, tips, or questions, so leave them in the comments!