A Simple AJAX Example for the Impatient Developer

Follow my erotic tale of "code awakening" as I discover AJAX's raw naked self.  We'll pop the hood and see AJAX as nature intended. This steamy tale of passion, romance, love, and AJAX may leave you breathless and panting for more. Or, it could simply be a ruse to get you to read my article. I'm not above shameless marketing tactics.  Sex sells and you're buying... ;-)

 

"Wam-Bam" AJAX

The following example is not valid, has no error checking, is messy, but it will work in IE7, Firefox, Opera, and Safari. It is the least amount of effort (I think) needed to demonstrate AJAX.  We will use two files for this example to show that a basic html page can pull information from a separate file on the server. No gender roles are defined for either of these files so, just pick your pleasure, open your imagination, and read on...

Content.txt

You're hot!

Default.html

<script type="text/javascript">
        var xmlHttp = null;                
        window.onload = function() {
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "Content.txt", true);
            xmlHttp.onreadystatechange = onCallback;
            xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            xmlHttp.send(null);            
        }        
        function onCallback() {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    alert(xmlHttp.responseText);
                }
            }
        }
    </script>

What's this do?

As Default.html loads in the browser, the JavaScript creates a new HTMLHTTPRequest and then uses it to retrieve the contents of the text file from the server. The results are displayed in an alert box. It sure doesn't feel like the warm snuggly AJAX we're looking for, but it's a nice little piece of AJAX to peak our interest.

 

"Second Date" AJAX

Okay. We got "the deed" done in the first example, but this little quickie just won't cut if we're serious about this little trist. Let's turn the lights on and get a better look at the example in a valid HTML page, with some basic error checking, and a few comments so we know what we are dealing with.

Content.txt

You're hot AND thoughtful!

Default.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>
    <title>AJAX Example</title>
    <script type="text/javascript">
        var xmlHttp = null;
        
        window.onload = function() { // Begin the request when page loads
            loadXmlHttp(); 
            sendRequest("Content.txt")            
        }
        
        function loadXmlHttp() {
            // Do a little browser detection to see if we can
            // use XMLHTTPRequest or if we are stuck w/ the ActiveX
            // option.
            if (window.XMLHttpRequest) { //IE7, Mozilla, Safari, Opera
                xmlHttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try{
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE5 & 6
                }
                catch(e) {}
            }
        }
        
        function sendRequest(url) {
            if (xmlHttp) {
                xmlHttp.open("GET", url, true); // "true" creates an async. request
                xmlHttp.onreadystatechange = onCallback;
                xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xmlHttp.send(null);
            }
        }
        
        function onCallback() {
            // This function will run over and over as the request 
            // goes though processing
            if (xmlHttp.readyState == 4) { // "4" indicates the end of the request
                if (xmlHttp.status == 200) {// "200" indicates a successful request
                    alert(xmlHttp.responseText); //Display the result
                }
                else { //Something went wrong.
                    alert('Error: ' + xmlHttp.status);
                }
            }
        }
    </script>
</head>
<body></body>
</html>

What's this do?

Basically, we took a "drunken one-night stand" of an example, and took it out for dinner.  The output is the same, but you can see that we are being a little more careful by loading the correct request object and checking to see if the request was successful. It's still pretty shallow and not something worth committing to, but it's starting to get interesting.

 

"Falling in Love" w/ AJAX

Now that we have the mechanics down, we can get a little adventurous and begin to spice things up. Let's add some of that hot AJAX interactiveness everyone's talking about and see what happens.  For this example, we will ask a question on the HTML page, wait for a response, and then see the response from the text file without any of that flacid postback action. The juicy bits have been highlighted in the code for your veiwing pleasure.

Content.txt

Of course I love you, AJAX!

Default.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>
    <title>AJAX Example</title>
    <script type="text/javascript">
        var xmlHttp = null;
        
        function askBigQuestion() {
            var l = document.getElementById('Loading'); // Find the loading object
            l.innerHTML = "I'm thinking..."; // Display some feedback during the process
            loadXmlHttp(); 
            sendRequest("Content.txt")            
        }
        
        function loadXmlHttp() {
            // Do a little browser detection to see if we can
            // use XMLHTTPRequest or if we are stuck w/ the ActiveX
            // option.
            if (window.XMLHttpRequest) { //IE7, Mozilla, Safari, Opera
                xmlHttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try{
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE5 & 6
                }
                catch(e) {}
            }
        }
        
        function sendRequest(url) {
            if (xmlHttp) {
                xmlHttp.open("GET", url, true); // "true" creates an async. request
                xmlHttp.onreadystatechange = onCallback;
                xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xmlHttp.send(null);
            }
        }
        
        function onCallback() {
            // This function will run over and over as the request 
            // goes though processing
            if (xmlHttp.readyState == 4) { // "4" indicates the end of the request
                if (xmlHttp.status == 200) {// "200" indicates a successful request
                    var r =document.getElementById('Result');
                    r.innerHTML = xmlHttp.responseText; // Display the result
                    var l = document.getElementById('Loading');
                    l.innerHTML = ''; // Clear the feedback
                }
                else { //Something went wrong.
                    alert('Error: ' + xmlHttp.status);
                }
            }
        }
    </script>
</head>
<body>
    Do you love me?
    <input type="button" onclick="askBigQuestion();" value="Ask"/>
    <br /><br />
    <span id="Loading"></span>
    <span id="Result"></span>
</body>
</html>

What's this do?

When the user clicks on the button, the request begins, a status message is displayed while the request is processed, and then the contents of the text file are rendered on the page. Hmmm...maybe not as sexy as we were hoping for, but the potential is definitely there for some very hot action.

 

The "Big Commitment"

It's decision time. How much farther do we want to go with this AJAX thing?  After this point, it's a big commitment (at least for me) to learn more JavaScript, understand the DOM, meet the relatives (JSON, REST, SOAP, etc), and a whole host of other freaky-deaky things. 

Personally, I am not ready for a full on commitment just yet. I am just going to finish reading my new book that I won from Dave Ward on his blog, "ASP.NET AJAX in Action" so I know how my "AJAX framework de jour" really works. Other than that, I'll and keep "playing the field" with some other technologies I've been flirting with--I'm such a tech whore--and let the smart people keep creating great frameworks that are so easy, even I can use them. 

Whew...I don't know about you, but I need a nap...


Thursday, 24 January 2008 17:19

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading