Computer Magic
Software Design Just For You
 
 



The AJAX primer

Good morning all. Today we will try to demystify the whole AJAX evolution. Lets start by breaking down the acronym. The first letter (A) stands for asyncronous. This simply means that more than one thing can happen at once. Have you ever been using a program, and you click a button and it seems to just freeze? This is an example of a program that is not asyncronous. It can only do one thing at a time. With AJAX, you can have multiple request going independant of each other without the main interface (the web page) suffering. This is very important as your browser can use AJAX to load information without interrupting you. The old non AJAX solution for communicating with the server would be to refresh the entire page, during which time you could do nothing until the process was complete (non asyncronous mode). The browser giants decided that they would include the abillity to make a request back to the web server without refreshing the page. This gave birth to the object HTTPRequest. This object can run in asyncronous mode and simply emulates the underlying mechanism used by the browser that makes the request to the server and gets back the response (generally the response is the rendered page). It is this new feat (the ability to make a request without refreshing the whole page) that gave birth to what we now think of as AJAX. Everything else was already possible before.

Next, the JA stands for JavaScript. JavaScript (not to be confused with Java, which is a different programming environment) is the scripting language that you can embed into your web pages. This language can take advantage of the DOM object model which allows you to locate and manipulate items in a web page. For instance, creating a DIV tag and giving it a name will allow you to write JavaScript that can update its contents without having to refresh the whole page. Here is an example.



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>
<DIV id=test></DIV>
<SCRIPT language="javascript">
$('test').innerHTML = "It Works!";
</SCRIPT>

Before this example will work, you will need to downlod the prototype library. We will talk about this more in a minute.

The previous script uses the DOM object model to update the contents of a DIV tag on the page. This can happen in real time without having to refresh the whole page. The code here happens when the page loads, but it could be easily tied to a button click or some other event. Even though this can change the page, what you really want to do is to get the current information from the server and put it in the DIV tag. JavaScript is the glue that holds all these capabilities together. It can manipulate the HTTPRequest object and put returned information into the page using the DOM object model.

Finally, the X in AJAX stands for XML. The idea is that XML is a great generic data description language and can be used to transport information in a logical and understandable format from one process to another (like communications between a server and a client browser). By using the XML spec, you can transfer raw data without having to send all the formatting information along with it and let the client JavaScript decide how to deal with this information. Now JavaScript can query just about any source (so long as it is on the same server) looking for information to update the current page with. Mostly, because I am lazy, I go ahead and return formatted data from an AJAX request and just slap the results into the page (saves me from having to interperate the XML). Which technique you use depends on your needs.

The different pieces together all add up to form the AJAX specification. AJAX is really a concept rather than an actual implementation. Most AJAX libraries include more than just the ability to make the request to the server. Once popular libary is Prototype. This library includes many other features like shortcuts to your elements, cross browser support, form serialization, etc. These features can be great time savers even if you don’t take advantage of the ability to make asyncronous requests to the server. Once such example is the abillity to refer to a element (with its ID defined) by name. This shortcut takes care of cross browser issues and makes the element avaialble to you in a clear and concise fashion.



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>
<DIV id=test></DIV>
<SCRIPT language="javascript">
$('test').innerHTML = "It Works!";
</SCRIPT>

The bold line shows how you can use the $ function to reference the DIV tag in question. Now try referencing that element in Internet Explorer, then in Netscape and tell me you can support both browsers easier. Even if you don’t want to use AJAX in your web application, if you use JavaScript at all, you should consider the time you will save by using a library like this.

For any of the prototype features you need to make sure that you include the JS file by using the following line:



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>

This just loads the JS file with all the objects and code so that it is available for use by the current page.

Now that we have that stuff out of the way, lets look at how we can use AJAX to do some cool stuff. First we will look at grabbing some content from another page and slapping it into ours without having to refresh the entire mess. We will not use the XML capabilities in this example. This is the simplest way to utilize AJAX. (NOTE: the following example may/may not work in non IE browsers, if not, add FORM tags around the INPUT tag)



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>
Show Google Results!
<INPUT type=button value="Get Results" onclick="new Ajax.Updater('content', 'http://www.google.com/search?hl=en&q=test', {asynchronous:true, method: 'get'}); return false;" />
<DIV id=content></DIV>

When you click the button, you will have a list of Google results listed in your page. It is that easy! Lets talk about what we just did, then we will set it up so that you can type in your own search string to get google results.

Before we show the next code snippet, notice that our DIV tag was named content and that we used ID rather than the NAME attribute. This is important as the Prototype library works off of IDs.



<INPUT type=button value="Get Results" onclick="new Ajax.Updater('content', 'http://www.google.com/search?hl=en&q=test', {asynchronous:true, method: 'get'}); return false;" />

The DIV tag is just a DIV tag with a name so that we can identify it. We create an INPUT button that allows us to click something. The button itself by default doesn’t do anything unless we write its OnClick event. When the button is clicked, we can start the AJAX code that will go get the specified web page and put the results into the item we name (our DIV tag named content). The new keyword creates a new instance of the AJAX Updater object. This will do not only the work of getting the results from the google server, but also will put the results into our DIV area. The Updater method needs some information to do its job. First we supply where we want our results to be displayed (‘content’, the name of our DIV tag). If this is left blank or you put an invalid name in here, then you just wont see any results (you may want this in some cases).

The next thing we need to tell the Updater method is what page to request. In our case, we asked for the search results from google for the word test. Go to google and type test in the search box, then hit the search button. Notice the URL in the address bar changes. I simply copied and pasted this. You can put any URL in here that you like (your own, your friends, etc..).

The last thing we send to the Updater method is an array of flags (hence, the {} symbols). This array of flags tells how to send the information (GET or POST, etc..). One flag deals with Asyncronous or non Asyncoronous mode (well go get the page in the background or will monopolize the current process while it does so). There are many options here which we will explore further.

And finally, after we call the Updater method, we return false. This will keep further events from happening. Here it isn’t such a big deal if you forget it, but I like to attach AJAX calls to a form which, if you don’t return false, you end up with a page refresh. This happens because the form is meant to request a whole new page and display it (what we are trying to avoid!). By returning false, we can cancel the submit (our AJAX call runs in the background still, so everyone is happy).

Lets add the ability put in our own search string and get back the Google results. We need to add FORM tags and an INPUT tag so that we can have a text box for our user to type in their search result. Also, we will change our previous INPUT from a button to a submit button. It is a special kind of button that will cause the current form to submit. We no longer need an OnClick attribute as the form will handle things from here. The for has its own attribute called OnSubmit that fires when the form is being sent.



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>
Show Google Results!
<FORM METHOD="POST" onsubmit="new Ajax.Updater('content', 'http://www.google.com/search?q=' + $('q').value, {asynchronous:true, method: 'get'}); return false;">
<INPUT type=text ID=q>

<INPUT type=submit value="Get Results" />
</FORM>
<DIV id=content></DIV>

We don’t actually let the form submit (the return false is there) but we do submit our information via the AJAX Updater method. Where we specify the URL to submit to, we add the value in our text box. Give it a try, you can now have search results right in your own web site.

Some might ask, why couldn’t we have just modified the OnClick attribute of the button rather than adding all the form tags and such? Look at the note above that snippet of code. Some browsers do not like INPUT tags outside of FORM tags and won’t display them correctly. This is the method that is least likely to cause you trouble.

One last addition before we go. We will add a parameter to the google search that will show only results from your own site. Go to google and type test site: www.cmagic.biz. This will show you only results from my site. Look at the resulting URL and put that into the previous example. Now, you can show only results from your site! Here is the code again with the change.



<SCRIPT src="prototype.js" type="text/javascript" ></SCRIPT>
Show Google Results!
<FORM METHOD="POST" onsubmit="new Ajax.Updater('content', 'http://www.google.com/search?q=' + $('q').value + ' site: www.cmagic.biz', {asynchronous:true, method: 'get'}); return false;">
<INPUT type=text ID=q>

<INPUT type=submit value="Get Results" />
</FORM>
<DIV id=content></DIV>

As you can see, AJAX can do some very cool stuff rather easily. We didn’t even show the ability that the prototype library has to wrap up all your forms variables for you in one call, or how it can utilize XML results to send just the data (rather than the fully rendered results).

If you decide to try AJAX out in one of your own projects, don’t try to roll your own. Use one of the available packages out there and save yourself some time and headaches. If you don’t want to use AJAX in your projects, but you do use JavaScript, think about using a library like prototype just because of the convenient way in which you can manipulate your page content in a platform neutral way.

Ray Pulsipher

Owner

Computer Magic And Software Design

Comments are closed.


Home | My Blog | Products | Edumed | About Us | Portfolio | Services | Location | Contact Us | Embedded Python | College Courses | Quick Scan | Web Spy | EZ Auction | Web Hosting
This page has been viewed 863987 times.

Copyright © 2005 Computer Magic And Software Design
(360) 417-6844
computermagic@hotmail.com
computer magic