An AJAX GET Request

Well, a fairly old theme. But, that does not mean that everyone knows it. Here’s a bit of some code and a short explanation of how it works. If short is not for you, post a comment and I’ll be sure to answer. Let’s go top to bottom, now 🙂

function submitForm()
{
	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	}
	else
  	{
		// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
    			document.getElementById("returnHtml").innerHTML = xmlhttp.responseText;
    		}
  	}
	xmlhttp.open("GET","my-page.php?p1=1&p2=123", true);
	xmlhttp.send();
}

And the HTML, now:

Well, there we go.
Now, once you click that button, submitForm() is called. We first essentially check whether it’s a Microsoft browser or a more compliant with the standards browser, and thence fore instantiate an object accordingly. We then tell the object that once it’s state has changed, we would like to do something. Namely, check whether the state in which the object currently is is something we are looking for (2 = Ready), and the status of our http request (200 being ok). Now, if those two are good… We simply pick up whatever was returned from our little trip to somewhere on the net and show what that url returned in a div.
Simple, yes. And if you feel like you know, great. Let those who don’t – know. 🙂

This entry was posted in AJAX and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *