Back to vBulletin 3 Articles

[Tutorial] Developers Introduction To AJAX Technology
by Zero Tolerance 17 May 2005

Note: In an effort to keep discussion on track, any questions you have towards me un-related to the tutorial itself, please feel free to PM me.

Hey there, I thought since developers will like to use AJAX technology in future modifications perhaps, it would be good to have some form of tutorial, explaining how to set up a basic XJAX engine

Notice: This tutorial is aimed at developers, or at least those who have generic knowledge of JavaScript/XML.
- Also, please don't steal my tutorial, if you wish to post it on other sites, then leave a directing link back to this thread as a source of origin, thanks

What is 'AJAX'?
To start with, AJAX stands for Asynchronous JavaScript and XML, don't worry about the word 'Asynchronous' just yet, we'll come to that later. So what is it/does it do?
Well to put it as simply as possible, AJAX allows a web application to send and receive data via a XML HTTP request - with absolutely no page refreshing at all! I'm sure you could think of endless possibilities where it could be implemented to make things so much better, faster, and more user friendly.

How does AJAX work?
AJAX technology is built on 2 main languages, 1 is optional, but they are JavaScript and XML, the JavaScript is the code that will do most of the work, while the XML is just a format of response, the XML however is optional, you can use a XMLHTTP request without actually calling an XML file, however you will be unable to use the pre-defined methods in JavaScript to call objects within the XML file, so you'd have to build your own parse engine if you decided to turn your own data that isn't XML.
A 3rd part, which again is optional, but most likely what you will use, is a dynamic server-side script, such as PHP, you could use this to output 'dynamic' XML files which contain different data depending on conditions set.

Enough! I want to see a working example!
Okay, let's not rush into things. First of all lets run through a JavaScript function which will initiate a XMLHTTP request.
The request is different for IE, than it is for other browsers, in IE you would have:
Code:
Request = new ActiveXObject("Microsoft.XMLHTTP")
While in Mozilla/Netscape etc.. you would have:
Code:
Request = new XMLHttpRequest()
So to make the request work on all the browsers, i would suggest using:
Code:
	IE = (window.ActiveXObject)? true : false
		if(IE){
		Request = new ActiveXObject("Microsoft.XMLHTTP")
		} else {
		Request = new XMLHttpRequest()
		}
Okay, to that’s the request object, next we want to set up a state change, this will call to another JavaScript function, which in turn will check the state of the XML request, if it's loaded, or failed, or ready to use. This is done like so:
Code:
Request.onreadystatechange = collectData
We'll worry about the collectData() function after we've gone through the rest of this function. Next up, we want to specify the request, such as the URL, method of request (POST/GET etc...), and if we will use 'Asynchronous' or not.

Asynchronous:
This is a parameter available in the request specification, if set to true, the script on the page will continue to run while the server is still loading the request, while if it is set to false, it will lock and stay locked until the request has finished loading. This can cause problems if the request is not found for whatever reason it may be, so setting it to 'true' be a must really.
Okay, so how do we set the request?, let's see..
Code:
Request.open(method,location,async,username,password)
The method is usually "GET", unless you specifically want "POST", the location is the location of the request, i.e.: data.xml, async is Asynchronous, remember we want that to be true, and the username & password variables are for authentication, if the page requires it, if not just ignore them.
So a basic request would be:
Code:
Request.open("GET", "data.xml", true)
No we're nearly done, just one more thing - send the request!
Code:
Request.send('')
You'll notice the parameter in the send() function is blank, leave it as this, Mozilla complains if it is not specified, you can even set it to null, just as long as it is not ignored.
Okay, so lets see what the whole function would look like:
Code:
	function requestData(Location,Handler){
	IE = (window.ActiveXObject)? true : false
		if(IE){
		Request = new ActiveXObject("Microsoft.XMLHTTP")
		} else {
		Request = new XMLHttpRequest()
		}
		if(Request){
		Request.onreadystatechange = collectData
		Request.open("GET", "data.xml", true)
		Request.send('')
		}
	}
Next up - collectData(), as said above, this function will determine if the request is complete and ready for use, making it safe really before we attempt to try do anything more. It's a really simple function, so I’ll just paste it down and show you how it works.
Code:
	function collectData(){
		if(Request.readyState == 4){
			if(Request.status == 200){
			// Code Execution Here
			}
		}
	}
Okay, we check first in an if conditional that the state of the request is 4, which means it has loaded. Next we check that the page status is 200, which is 'OK'. After that you're ready do your nifty bits of programming to make things fancy.

The Example
In this example, i have slightly modified the 2 functions above to include a parameter for usage, I’ll explain it below.
We assume that 'data.xml' has the following contents:
Code:
<?xml version="1.0" encoding="iso-8859-1" ?>
<data>
<username>Zero Tolerance</username>
<userid>1</userid>
</data>
The task: Pull out all username and userid from XML using AJAX.

Okay, so here's my javascript:
Code:
<script type='text/javascript'>
<!--
	function requestData(Location,Handler){
	IE = (window.ActiveXObject)? true : false
		if(IE){
		Request = new ActiveXObject("Microsoft.XMLHTTP")
		} else {
		Request = new XMLHttpRequest()
		}
		if(Request){
		Request.onreadystatechange = function(){collectData(Handler)}
		Request.open("GET", Location + '&nocache=' + Math.random(0,9999), true)
		Request.send('')
		}
	}
	function collectData(Handler){
		if(Request.readyState == 4){
			if(Request.status == 200){
			eval(Handler + '(Request)')
			}
		}
	}
	function parseData(Request){
	Data = Request.responseXML.documentElement
	User = Data.getElementsByTagName('username')[0].firstChild.data
	UID  = Data.getElementsByTagName('userid')[0].firstChild.data
	document.getElementById('data').innerHTML = '<b>Username:</b> '+User+'<br /><b>UserID:</b> '+UID
	}
requestData('data.xml','parseData')
-->
</script>
You'll notice the requestData() & collectData() have a new parameter as said earlier, this is to allow one function to call XMLHTTP request, but allow another function to parse the data once it has been collected, so you don't have to specify tons for different functions over and over for different XMLHTTP requests.

Apart from that, the function parseData() is the only one added, this is the handler for the XML data. Request.responseXML.documentElement will return the document for the XML, which is an object, note that if you have not sent a valid XML file over, then you may not use this method, it will appear as null (also if your using php to generate a dynamic XML file, don't forget to add header('Content-Type: text/xml');!).
If you know JavaScript already then you will know how getElementsByTagName('tagname') works, it basically returns the tag with the name specified, and the 0 at the end specifies we want the 'first' occurrence of this tag, so we grab the username and userid tag, get the data it has, then send it into an element on our page with the id 'data', such as:
Code:
<div id='data'></div>
Once loaded in your browser, you should see:
Username: Zero Tolerance
UserID: 1
Or unless you changed the data in the XML file ofcourse..

If you wanted to send non-XML data via a XMLHTTP request, then you can call the whole file contents once the data has been collected by collectData(), to call it, simply put:
Code:
alert(Request.responseText)
You will see a pop up with all the contents of the file, just store that in a variable and you're ready to make your own parser for it, if the predefined js methods just don't do it enough for you

Alright, i think I’ve covered everything that needs to be said, to finish off, I have attached a file 'ajax.php', which includes the XML output (via php) and the JS AJAX engine, all in 1, simply upload it to your server to give it a go

I hope this has been of some help to you.

- Zero Tolerance
Attached Files
File Type: php ajax.php (1.2 KB, 457 views)

vblts.ru supports vBulletin®, 2022-2024