ramar.work

More Than You Wanted to Know about XMLHTTP

I’m starting to get more questions on what I consider to be basic AJAX usage. So, to make sure that I’m explaining it correctly and so that others who aren’t really familiar with it understand it, I’ve penned a small guide to getting it working in your own applications. To better illustrate it, I’ll avoid jQuery or any of the other popular Javascript libraries and focus on what actually happens.

At its simplest, there are just four calls to make a basic AJAX implementation work. The usage goes something like this:

var xhttp = new XMLHttpRequest();
xhttp.open( “GET”, “http://somebody.com/file_from_server.txt”, false );
xhttp.send();
console.log( xhttp.responseText );

This code is asking for the file “file_from_server.txt” from http://somebody.com. We specify how to retrieve that file with the first parameter to xhttp.open. In this case we use GET because we aren’t sending any additional data. However, if we wanted to send some other binary data along with the request, we’d use either POST or PUT. I’ll be sure to go into more detail with this later. The second argument tells the browser what file to look for. And the final parameter tells the browser to wait until a response is received from the server before moving on to the next set of instructions. If we change this parameter to true, the browser will create another thread and do all of the sending and receiving in the background. This thread creation allows the browser to engage in what’s known as asynchronous communication, where the client and server can communicate when resources are available.

Now the key takeaway here (and one of the reasons I’m explaining all of this) is that file_from_server.txt could be just about anything. Often, it could be a file, but it could simply be an endpoint for uploading new files. It might simply be a page stub that creates new files on receipt of some code from the user. Either way, though, it’s the beginning of an API—the standard for most modern web applications today. With proper backend architecture, an application can share most of its data with another party through the use of simple HTTP requests.