Ajax load page to div avoiding race condition

How can you load multiple pieces of content into separate divs, much like frames but avoiding the javascript race condition. This was adapted from http://codesnippets.joyent.com/posts/show/602 The problem with the above snippet was that you could only make one ajax call at a time as the javascript used the global variable XMLHttpRequest. With help from http://www.the-art-of-web.com/javascript/ajax-race-condition/ I changed the ajax snippet to be object based and now you can load as many divs simultaneously on the sam page at once. However http requests are usually restricted to 2 per server but it's useful if your page grabs bits from several severs. I got round the cross domain problem with a simple php proxy script which i'll add soon.
  1. function AjaxRequest() {
  2.  
  3. var req;
  4.  
  5. this.ahah = function (url, target) {
  6.   document.getElementById(target).innerHTML = ' Fetching data...';
  7.   if (window.XMLHttpRequest) {
  8.     req = new XMLHttpRequest();
  9.   } else if (window.ActiveXObject) {
  10.     req = new ActiveXObject("Microsoft.XMLHTTP");
  11.   }
  12.   if (req != undefined) {
  13.     req.onreadystatechange = function() { ahahDone(url, target);};
  14.     req.open("GET", url, true);
  15.     req.send("");
  16.   }
  17. }
  18.  
  19. var ahahDone = function (url, target) {
  20.   if (req.readyState == 4) { // only if req is "loaded"
  21.     if (req.status == 200) { // only if "OK"
  22.       document.getElementById(target).innerHTML = req.responseText;
  23.     } else {
  24.       document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
  25.     }
  26.   }
  27. }
  28.  
  29. this.load = function (url, target) {
  30.         this.ahah(url,target);
  31.         return false;
  32. }
  33.  
  34.  
  35. } //end of class
This also has to go in the head of the document
  1. function callAjax(url, target) {
  2.   var req = new AjaxRequest();
  3.   req.load(url, target);
  4.   return true;
  5. }
Call code with the name of the external file you would like loaded into the div and the id of the div you want to put the content into
  1. <a href="file1.html" onclick=callAjax"('file1.html','content');return false;">File 1</a>
  2.  
  3. </javascript>

Category:

Add new comment

Full HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.