FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

AJAX tutorial

 


phervers
you might have heard of AJAX already, if not let me explain a bit. AJAX stands for Asynchronous Javascript and XML. It's not really a new thing but once google put it into good use in their google maps, everyone wants some too. Basically it allows changing of a page contents without reloading the whole page. So you can for example make a shoutbox which will not reload your whole page to check for new messages, or make a multi-tabbed web app which will work like a breeze. It's not realy very difficult but to make it even easier i'll give you a nice script you can use.

ajax.js
Code:

// You can edit those messages if you want to
var loadingMessage     = "<em>Loading ...</em>";
var errorMessage       = "<em>Error %n has occured</em>"; // %n will be replaced with error number
var unsupportedMessage = "<em>Your browser does not support XMLHttpRequest ! Get Firefox</em>";

// loadToElement - loads contents of a file into element that supports innerHTML property like <div>
// file_url        -    url of the document you want to load
// element_id   -   id of the element you want to load to

function loadToElement(file_url, element_id) {
   var req;
   
   // Native XMLHttpRequest support (Mozilla, Opera)
    if(window.XMLHttpRequest) {
       try {
         req = new XMLHttpRequest();
        } catch(e) {
         req = false;
        }
    //  IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
          try {
           req = new ActiveXObject("Msxml2.XMLHTTP");
         } catch(e) {
           try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
           } catch(e) {
                req = false;
           }
      }
    }
    var element = document.getElementById(element_id);

   if(req == false)
   {
      element.innerHTML = unsupportedMessage;
      return;
   }


   //Display loading message
    element.innerHTML = loadingMessage;
   //start the request
    req.open("GET", file_url, true);
   
   //define function for state changed event
    req.onreadystatechange = function() {
        if (req.readyState == 4)
      {
         if(req.status == 200)
         {
            // Loading was successful now put loaded content into element
            element.innerHTML = req.responseText;
         }
         else
         {
            // There was some error show info
            element.innerHTML = errorMessage.replace("%n", req.status) + "<br>" + req.statusText;
         }
        }
    }
   // send the request parameter is required by some browsers
    req.send(null);
}


Soo what does that do ? I will not be explaining this line by line cause if you know javascript you can easily read the code, and if you don't you wouldnt understand anyway Wink.

Basically it provides you with a function that wraps up simple ajax functionality of loading content into a div. I will provide you with one example of how to set this up.

1. Copy script contents and put it into a file called ajax.js.

2. Then create a file called 1.htm, add a link to your script file, then put a button and a div into it. Div's id should be "contentDiv", also add an onclick event to your button like onClick="loadToElement('2.htm', 'contentDiv');". Your code should look like this :

1.htm
Code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">
<title>Ajax test</title>
<script src="ajax.js"></script>
</head>
<body>
<input type="button" onClick="loadToElement('2.htm','contentDiv');">
<div id="contentDiv"></div>
</body>
</html>


3. Finally create file called 2.htm and put some content into it. Note that it should not have <html> or <body> tags inside something like

2.htm
Code:

<strong>AJAX works !</strong>


Now load 1.htm into your browser and try clicking the button.
Ofcourse you need to set this up on your web server. If you got any questions or comments go ahead. If there's an interest in this i might improve that script further adding form submitting capabilities.

ps. here's a crunched version of the same script if you want to keep your site loading fast.
Code:

var lM="<em>Loading ...</em>";
var eM="<em>Error %n has occured</em>";
var uM="<em>Your browser does not support XMLHttpRequest ! Get Firefox</em>";
function loadToElement(g,f){var a;if(window.XMLHttpRequest){try{a=new XMLHttpRequest();}catch(e){a=false;}}else if(window.ActiveXObject){try{a=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{a=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){a=false;}}}var c=document.getElementById(f);if(a==false){c.innerHTML=uM;return;}c.innerHTML=lM;a.open("GET",g,true);a.onreadystatechange=function(){if(a.readyState==4){if(a.status==200){c.innerHTML=a.responseText;}else{c.innerHTML=eM.replace("%n",a.status)+"<br>"+a.statusText;}}};a.send(null);}
Reply to topic    Frihost Forum Index -> Miscellaneous -> Tutorials

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.