Jump to content
xisto Community
Sign in to follow this  
bluefish1405241537

Ajax: Introductory Tutorial XML, XMLHttpRequest/ActiveX, tutorial

Recommended Posts

In this tutorial I will attempt to introduce you to the basics of AJAX programming.

 

AJAX is basically the name given to a type of programming combining server-side and client-side scripting to create a seamless web application that is both secure and functional. It has all the benefits of web sites and regular applications. Here are a few key features that attract so many people to this type of programming:

-Instant feedback to user

-No waiting for pages to load because loading is done in background

-Easy communication with server to allow security and functionality at a good speed

-With a standard web site you need to wait for the browser to not only download a page but also render it. With AJAX, that wait is gone: it is displayed almost as soon as it is downloaded

 

AJAX (usually) uses to following technologies:

-JavaScript, for server side scripting

-HTML, CSS, DOM, etc. to render page for user

-A server side scripting language (it is irrelevant which one)

-XML for communication between server and client, usually used by server to client communication

 

Since we are in the JavaScript section, I will assume that you are comfortable with JavaScript. I will first give you an introduction to XML. If you are already comfortable with XML, you may skip this section.

 

XML

XML is basically a way to describe objects. Objects are organized in a hierarchy. The opening part of a (sub)hierarchy is represented by <NAME>, where NAME is the type of object. The end of an object is represented by </NAME>. You should recognize this as being similar to HTML. It is. Since you should already know HTML, I will simply compare them.

 

-XML is much more strict than HTML, and your pages must comply, otherwise it should generate errors

-A page is started by

<?xml version="1.0"?>
-After the <?xml?> tag, the rest of the document must be enclosed within a single pair of tags

-Every tag may have attributes. Attribute values must be enclosed within double quotes

-Whitespace is preserved, but ignored by the parser except when data is extracted

-Objects are referred to as child nodes of those directly above them

-Each object also has a text node, which is the text within the opening and closing tags

For more specific specifications, please refer to W3C - they have a good tutorial.

 

Here is a sample XML document:

<?xml version="1.0"?><Xisto><tutorial type="programming/javascript"><post><title>AJAX</title><description>Learn AJAX</description><author>bluefish</author><content>hi</content></post></tutorial></Xisto>
As you can see, in this example I described this post. In general, the attributes are used to give detail on the actual data, and should not represent data. To get a more advanced knowledge, click on W3 Schools XML Tutorial.

 

The Basics of Interaction

Now we should know the basics of the technologies described above (with the possible exception of DOM and/or CSS). I will show you the JavaScript object that allows for AJAX to happen:

 

The XMLHttpRequest Object

Or, as Microsoft likes to call it, ActiveXObject("Microsoft.XMLHTTP")

As a side note: I recommend Firefox browser with the Firebug extension. Firefox follows the W3C recommendations, and there is no debugger around that compares with Firebug for AJAX programming.

Now, to use this object, we should use a code like the following:

var t;if(window.XMLHttpRequest)t = new XMLHttpRequest();else if(window.ActiveXObject) //Internet Explorert = new ActiveXObject("Microsoft.XMLHTTP");elsealert("Your browser does not support XMLHttpRequests!");
This creates t as an XMLHttpRequest if it exists, otherwise tries ActiveXObjects, and should it fail that, gives a message that it failed.

 

Then we need to make it do something. First, we need to assign a handler function for when it loads.

t.onload = myfunction;function myfunction() {alert("Hi! We got our request back!");}

Simple enough? Good.

The generally recommended method of passing data to the server is via GET data, which is basically embedded in the URL you send. For example, "astahost; contains three get values: post, new_post, and 93, indexed by act, do, and f, respectively.

 

Now we're ready to pass data to the server.

t.open("GET", page, true);t.send(null);
Simple? Good. GET is the type of data we are passing. page is the variable containing our page url, possibly with GET data. The last argument indicates that we are using asynchronous mode, which allows the handler function to be called instead of looping until a response is received, which can cause many problems. The section function is unimportant but necessary. Now all we need to do is wait for the information to be received! Here is a function a created to encompass a request.

 

function createRequest(page, handler) {if(window.XMLHttpRequest) {req = new XMLHttpRequest();} else if(window.ActiveXObject) {req = new ActiveXObject("Microsoft.XMLHTTP");} else {alert("Your browser does not support XML HTTP requests! Please switch to a different browser before using this website.");return false;}req.onload = handler;req.open("GET", page, true);req.send(null);return req;}

As you can see, it uses all the parts we introduced. We would use it like so:

myRequest = createRequest("hello.php", responseHandler);function responseHandler() {//Do stuff with myRequest}

The only thing we have left to do is receive the actual data. There are two relevant properties that we can use in our function: responseText, and responseXML. The text is simply the text of the response. The XML is an object representing the structure of the document, which contains several properties and methods. You can look them up, or you can use the handy function I created for your use (tried and tested):

 

function getValue(request, term) {/*term needs to be parsed, appears in form:a/b/cwhere b is child of a, c child of beach node can be "#1", where "1" is the index of the child nodeor "name#1" where "name" is the name of the type of node and "1" is the index of the nodes of that typeor just "name" which defaults to index 0 for that type*/try {var nodes = term.split("/");var current = request.responseXML;for(i=0;i<nodes.length;++i) {if(nodes[i].indexOf("#")==0) { //Type 1current = current.childNodes[nodes[i].replace("#","")];} else if(nodes[i].indexOf("#")>0) { //Type 2var s = nodes[i].split("#");current = current.getElementsByTagName(s[0])[parseInt(s[1])];}else { //Type 3current = current.getElementsByTagName(nodes[i])[0];}}return current.nodeValue;} catch(e) {throw new exception("Invalid XML document/query!");}}
It takes two arguments: the first is the request, and the second is a string that will be parsed to get data from the document. To use it, use a "/" as a divider, and have the node names. Alternately, you can use #0, where 0 is the index of the child node, or node#0, which takes the 0th element of node at that part of the hierarchy. For example, to get the value of the title of my message in the XML document above, I could use "Xisto/tutorial#0/post/title/#0". We need to add #0 at the end to get the text value.

 

Next, we need to use a server-side language to create the XML document. I won't walk you through that, but if you have any trouble, feel free to reply and I will assist you in any way I can.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.