Create Your First AJAX Request (Part One)

AJAX is now everywhere on the web. The ability to update content on the web page without reloading the page provides a slicker experience to the user whilst also reducing the load on the server (the server only needs to output the updated content and not the entire page).

The complete script can be downloaded here AjaxRequest (30.91 KB) Create your first AJAX Request :)

At the heart of AJAX is the JavaScript XMLHttpRequest object. This gives a web page the ability to communicate with a server asynchronously which means that the user can still interact with the web page while all the ‘behind the scenes’ work goes on.

In an ideal world, to create a new XMLHttpRequest object, all we would need to do is this…

var xhr = new XMLHttpRequest();

…but of course, as long as Internet Explorer 6 and below is around, it isn’t an ideal world. Because of IE, we have to try alternative ways of creating the XMLHttpRequest object. The following function (getRequestObj) uses a try/catch statement on IE’s ActiveXObject:

function getRequestObj() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) {
	try {
	    xhr = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch(e) {
	    try {
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	    }	
	    catch(e) {
	        xhr = false;
	    }
	}
    }
    if (!xhr) {
        alert("There was an error creating the XMLHttpRequest object.");
    } else { 
    return xhr;
    }
}

The above function first tries to create a XMLHttpRequest object using native browser support. If it can’t do that, it then tries the proprietry IE ActiveXObject. At the end of the function, we either have a XMLHttpRequest object created or an alert pops up telling the user there has been an error.

Go ahead and save that script (I’ve called mine ‘createxhr.js’). You now have the foundation for any AJAX functionality you desire. In part two, we’re going to create a simple script that shows a user’s profile details when you click on their name (yeah, I know this isn’t that exciting but it will take you through some of the basic methods and properties that belong to XMLHttpRequest).

Stay tuned :)

Feed IconFollow me on Twitter





3 Responses to “Create Your First AJAX Request (Part One)”

  1. [...] post:  Create Your First AJAX Request (Part One) Posted in PHP | Tags: ajax, heart, load, only-needs, page, page-provides, reloading-the, [...]

  2. [...] Read the original here: Create Your First AJAX Request (Part One) | ElanMan [...]

  3. This is a nice introduction to AJAX. I look forward to seeing what you do next!

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">