JAVASCRIPT: Load a page using AJAX

I just noticed that I use one little AJAX function to load all of my pages but haven’t took the time to explain to my readers how I do it yet, so here goes :) .

To use this create a HTML file with the following code and upload it to your web server..

[i]ajax.html[/i]
[code]
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
</head>

<body>
<p>
<a href="nonjs.html" onclick="get('content.txt', 'content');return false;">Click here to load our content using ajax</a>
</p>

<div id="content">
<p>
Our content.txt file will be loaded here when the link above is pressed.
</p>
</div>

</body>
</html>
[/code]

Now, the html file shows us a page with the text [i]Click here to load our content using ajax[/i]. When this text is clicked it makes a call to the function get() which is defined in the next file.. ajax.js

[i]ajax.js[/i]
[code]
function createhandler(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
return xmlhttp;
}
function get(url, divid){ //Url to fetch + div ID to insert content into
var xmlhttp=createhandler();
xmlhttp.onreadystatechange=function (){
if(xmlhttp.readyState==4){
document.getElementById(divid).innerHTML=xmlhttp.responseText;
xmlhttp.onreadystatechange = null;
xmlhttp.abort();
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
[/code]
This file defines the functions [i]get[/i] and [i]createhandler[/i]. The createhandler function is used to create our AJAX xmlhttp object used to send and receive data via ajax.

The [b]get()[/b] function takes the parameters [i]url[/i] and [i]divid[/i]. Then createhandler is called to make the xmlhttp object.

The code that begins [i]xmlhttp.onreadystatechange=function (){ [/i] is used to capture the onreadystatechange event and when readystate changes to 4 (READY) our divid is updated with the text taken from the url we specified.

The lines [i]xmlhttp.open(‘GET’, url, true);xmlhttp.send(null);[/i] send a HTTP GET request to the url we specified. The true paramater means that data can be sent and received asynchronously and does not concern us here.. Just be sure it’s true :) . We send null data to terminate the command.

Next all you need to do is create a content.txt file with some html code in it to be loaded. Here is an example:
[i]content.txt[/i]
[code]
<p>I have just been loaded with ajax using the function get(url, divID)</p>
[/code]

To use the example above, upload all of the files into the same directory on your webserver. I hope this gives you some insight on the basics of AJAX and how to load pages. If you have any questions please comment this blog :)

Love
Stephen

  • Share/Bookmark

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

WordPress Themes