The Web Design Magazine for All | Connecting Designers

Tuesday, 06 January 2009

 

Categories
AJAX
ASP.net
Basics Corner
CSS
Graphics 3D
PHP
SEO Ask the Expert
SEO General
Software Review
Web Applications
Extras
Latest News
Resource Directory
Contact Us

AJAX - A Special Kind of Bleach PDF Print E-mail
Friday, 02 December 2005
by Gabe Bell 


It seems like every person that has a hand in web design/development is into something called AJAX. It seems everywhere I turn I hear, “we could ajax it and save time on server requests”.  So what is Ajax? What does it do? How can it help me? What are the pros and cons?

So what is Ajax?         
Simply put Ajax is a branded cleaner from Colgate-Palmolive. (link)

It claims to be able to clean anywhere in your house, with a new “easy rinse formula”.  Ajax is also bleach-based so that the toughest stains are a little easier to remove.

Caution: From my experience with Ajax, it also bleaches your hands and clothes and burns terribly in cuts.

What does Ajax do?

The purpose of Ajax is to make cleaning your house a little easier. Use primarily on toilets, sinks, and showers for those hard to remove water stains. Since Ajax contains bleach the effect on white or off white porcelain is amazing.

Legal Note: I do not recommend trying to clean your $$ marble countertops with Ajax, I am not responsible for any damages caused by Ajax.

So how can Ajax help me?

Ajax can help you by helping clean your house more efficiently than ordinary non-bleach based cleaners. Got tough water stains? No problem, use Ajax. There is even an Ajax dish cleaner for those burnt hamburger grills.

Pros and Cons

Pros:
Cleans hard water spots. Bleach-based. Powdered form for applying quickly.

Cons:
Stains clothes. Peels skin off of hands. Hard to handle. Expensive.

So why are web gurus ranting and raving about a dangerous cleaner? Simple, they are not; they are referring to AJAX which stands for Asynchronous JavaScript and XML. Contrary to popular belief, AJAX is not a programming language, but is a term used to describe a group of various computer languages very much like .NET which is a group of various technologies.

The theory behind AJAX is that you don’t have to reload the entire page, just reload the content you need. For example, you want to validate an email but you do not want to reload the graphic-heavy form every time thus heavily burdening your server; you create an AJAX function that takes the email address, sends it to server for validation and then returns the result. AJAX still makes a call to your server but only uses a couple of bytes vs. a couple kilobytes, thereby reducing the load on your server and making the page appear as if it validated the email by ‘magic’ because there was no refresh of the page.  So what is AJAX? What does it do? How hard is it to write? How can it help me? Got any examples?

So what is AJAX?

Read the former paragraph for a more in-depth look. But for those skimming the article here it is in a nutshell; Asynchronous JavaScript and XML is a conglomerate of technologies used to make seamless, almost invisible calls to a server.

What does AJAX do?
Once again, explained in greater detail above. In a nutshell:  AJAX makes seamless, almost invisible calls to a server sending and retrieving data without the need for a page refresh.

How hard is it to write?
"People who do (AJAX development) are rocket scientists"[1] - Charles Fitzgerald, Microsoft’s general manager for platform technologies.

So is AJAX really that hard to write? The answer is no. You just need a common foundation of JavaScript and SGML-based languages (XML, HTML, and XHTML) and an understanding of server side scripting. I will show you later on in this article, how easy it is to write your very own stepping block AJAX function.

How can it help me?
Finally, a question I can answer. First let’s look at compatibility of AJAX in many of the world’s browsers:

Internet Explorer 4.0 + (hopefully)
Konqueror
Apple Safari 1.2+
Mozilla Gecko and derivatives
Opera 7.6+

So it looks like most browsers support AJAX, so the question is why is such a new technology so widespread? Simple, AJAX in all the browsers above except IE (which uses ActiveX for AJAX) use common JavaScript calls to perform AJAX functions.

This is all useless without a use, right?  Some examples of AJAX usage are: zip code validation, email validation, zip code lookup, search, preview of text, reference/verse lookup, etc.  Some well known companies use AJAX in their web applications, a list is below:

AOL AIM Mail - http:www.aim.com/
Google Maps - http:earth.google.com/
Google Mail - http:www.gmail.com/
Google Reader – http:reader.google.com/
MSN Virtual Earth - http:virtualearth.msn.com/

I encourage you to check out these examples of production-level AJAX applications to see what can be accomplished with AJAX.

Ok lets get down and dirty with AJAX, I will walk you through step-by-step on creating an asynchronous weather page, that allows the user to input a US zip code and receive the current weather conditions. We will be using the RSS feed from http:www.rssweather.com, the service is free but has a limiter on it for requests, so you might want to cache it.

First off AJAX cannot call to a page on another domain for security reasons. So AJAX developers use what is called a server proxy page. Samples below:

C# (my favorite language) - proxy.aspx

<%@ Import Namespace="System.Net" %>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
 if (Request.QueryString["url"] == null) {
   Response.Write("no url");
      return;
 }
 WebClient objWeb = new WebClient();
 string strUrl = Request.QueryString["url"];
 UTF8Encoding objUTF8 = new UTF8Encoding();
 Response.Write(objUTF8.GetString(objWeb.DownloadData(strUrl)));
}
</script>
VB.NET (via converter) – proxy-vb.aspx
<%@ Import Namespace="System.Net" %>
<script language="VB" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
       If Request.QueryString("url") Is Nothing Then
        Response.Write("no url")
        Exit Sub
      End If
    Dim objWeb as New WebClient()
      Dim strUrl as String  = Request.QueryString( "url" )
    Dim objUTF8 as New UTF8Encoding()
      Response.Write(objUTF8.GetString(objWeb.DownloadData(strURL)))
  End Sub
</script>
PHP (by request) – proxy.php
<?php
if(!@$_REQUEST['url']) {die("no url");}
$handle = fopen($_REQUEST['url'], "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents;
?>
For the client side of AJAX, I will be using Jim Auldridge’s excellent generic AJAX library. You will need to download it (right-click and Save Link/Target as..) to continue on with the examples. Documentation is also available for the generic AJAX library.

HTML document: ajax_weather.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>AJAX Weather</title>
<style>
.warning { font-size: 1.1em;  font-weight: bold;  }
.sWarn {color: red; font-size: 0.8em; margin: 0px;}
.icon { margin: 0px; vertical-align: middle; margin-right: 35px; margin-bottom: 15px;}
.temp {margin: 1.2em; }
h4 {margin: 0 0 0 15px; padding-top: 5px; text-decoration: none;}
h5 {margin: 0px; margin-top: 2px; }
dl, dt, dd {display: inline;}
dd {margin-left: 5px; margin-right: 5px; }
dt {font-weight: bold; }
body {background-color: #CCCCCC; font-family:Geneva, Arial, Helvetica, sans-serif;}
h3 { background-color:#CCCCCC;}
.weather { background-color:#999999; }
</style>
</head>
<body >
<div id="weather" class="weather"></div>
<p><label>Zipcode:</label><input name="zipcode" type="text" id="zipcode"><input type="submit" value="Lookup" ></p>
</body>
First off, we must include the AJAX library for use in our document like this:

<script type="text/javascript" src="XMLHttpRequest.js"></script>
Add the script tab between title & style but not before the meta tag. Next we set up the AJAX object:

<script  type="text/javascript">
function updateWeather(){
      zipcode = document.getElementById('zipcode').value;
var myDoc = AJAX.getDoc("proxy.aspx?url=http://www.rssweather.com/zipcode/"+zipcode+"/rss.php",'successMethod'," ",'errMethod');
}
</script>

Adding this after the script include, Line 2 is where we define the AJAX object by telling it the url to use, what function to use on success, what arguments to pass if successful, and what error function to use.


Next we add the error function, adding this before previous code:
function errMethod(){
      alert("Server returned:\n"+AJAX.xhr.status+" "+AJAX.xhr.statusText);
}
Then we add the success function, adding this after the previous code:

function successMethod(){
      alert(AJAX.xhr.responseText);
}
Add the onclick handler to the lookup button:

<input type="submit" value="Lookup" onClick="updateWeather()">
Test the application, type in a zipcode and click Lookup, it should pop up showing the raw RSS data. Congratulations! You have just created an AJAX application aka a Frankenstein.

We can change this to write out the data instead popping up by replacing the alert:
document.getElementById('weather').innerHTML = AJAX.xhr.responseText;
We can go further and parse the RSS so that only the current conditions are displayed:

title = AJAX.xhr.responseText.split("title>");
title = title[1].substring(0, title[1].length-10);
title = "<h3>Current Conditons for "+title+"</h3>";
results = AJAX.xhr.responseText.split("content:encoded>");
results = results[1].substring(9, results[1].length-5);
document.getElementById('weather').innerHTML = title+results;
HTML document: ajax_weatherFINAL.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>AJAX Weather</title>
<script type="text/javascript" src="XMLHttpRequest.js"></script>
<script type="text/javascript">
function successMethod(){
      title = AJAX.xhr.responseText.split("title>");
      title = title[1].substring(0, title[1].length-10);
      title = "<h3>Current Conditons for "+title+"</h3>";
    results = AJAX.xhr.responseText.split("content:encoded>");
      results = results[1].substring(9, results[1].length-5);
    document.getElementById('weather').innerHTML = title+results;
}
function errMethod(){
      alert("Server returned:\n"+AJAX.xhr.status+" "+AJAX.xhr.statusText);
}
function updateWeather(){
      zipcode = document.getElementById('zipcode').value;
      var myDoc = AJAX.getDoc("proxy.aspx?url=http://www.rssweather.com/zipcode/"+zipcode+"/rss.php",'successMethod',"",'errMethod');
}
</script>
<style>
.warning { font-size: 1.1em;  font-weight: bold;  }
.sWarn {color: red; font-size: 0.8em; margin: 0px;}
.icon { margin: 0px; vertical-align: middle; margin-right: 35px; margin-bottom: 15px;}
.temp {margin: 1.2em; }
h4 {margin: 0 0 0 15px; padding-top: 5px; text-decoration: none;}
h5 {margin: 0px; margin-top: 2px; }
dl, dt, dd {display: inline;}
dd {margin-left: 5px; margin-right: 5px; }
dt {font-weight: bold; }
body {background-color: #CCCCCC; font-family:Geneva, Arial, Helvetica, sans-serif;}
h3 { background-color:#CCCCCC;}
.weather { background-color:#999999; }
</style>
</head>
<body >
<div id="weather" class="weather"></div>
<p><label>Zipcode:</label><input name="zipcode" type="text" id="zipcode"><input type="submit" value="Lookup" onClick="updateWeather()"></p>
</body>    
There you have it, your first AJAX application albeit a tiny one but still one. As you can see from the AJAX Weather app that we made, AJAX is really simple to create if you use Jim’s generic AJAX library. Have fun inventing new uses for AJAX!


[1] Microsoft gets hip to AJAX: News.com, 06/27/05, http:news.com.com/Microsoft+gets+hip+to+AJAX/2100-1007_3-5765197.html?tag=nl


Gabe Bell is a freelance web developer who has experience tackling PHP and ASP.NET projects.

Only registered users can write comments.
Please login or register.





advertisement
 

 

Design Studio Magazine, PO Box 8145, Fort Wayne, IN 46898-8145

Unique Web Design and Development
for(var i=0;i