AJAX Communicate Function

November 14th, 2006 Leave a comment Go to comments

I've had a few requests to post my AJAX Communicate Function, so here it is. As you can see, you may pass four arguments to it. The first is 'method', which may be either GET or POST (defaults to GET), 'url' and 'querystring', which are self-explanatory, and 'failure'. The 'failure' argument may contain code to be evaluated in case of failure. This can be triggered due to anything from the server giving a 404 error to the user suddenly losing their network connection. This is optional, but useful.


I've commented this code so that programmers new to the concept of AJAX can hopefully learn something from it. Anyone can modify or distribute this function as they see fit. As a courtesy to its author, please credit me when you do so.
 
var request = new Array();
var timeout = new Array();
function communicate(method, url, querystring, failure) {
 /*
 AJAX Communicate function written by Mango - http://www.toao.net/
 The communicate function takes four arguments: method, which is GET or POST (defaults to GET),
 url and querystring, which are self-explanatory, and failure, which is evaluated in case of
 failure.  The onreadystatechange function does an eval() on the response from the server, so
 queries should return Javascript code to be executed.
 If this function is useful for you, please tell someone about it. 
 */
 
 /* Set requestid */
 var requestid = new Date().getTime() * Math.random();
 /* Set the cursor to "wait".  We want things to be pretty, don't we? */
 document.body.style.cursor = 'wait';
 /* Initialize the XMLHTTP Object */
 if (typeof window.ActiveXObject != 'undefined') {
  try {
   request[requestid] = new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e) {
   alert ("Error:  Could not create the Microsoft.XMLHTTP object.  Please contact your systems administrator.");
   }
  } else if( typeof XMLHttpRequest != 'undefined' ) {
  try {
  request[requestid] = new XMLHttpRequest();
  } catch(e) {
   alert ("Error:  Could not create the XMLHttpRequest object.  Please contact your systems administrator.");
  }
 } else {
 alert ("Error:  This browser does not support AJAX.  Please contact your systems administrator.");
 }
 request[requestid].onreadystatechange = function() {
  /* This is a slightly confusing part of the script.  We don't wait to hear back from the server before we continue
  with the communicate() function.  It sends the request, and if and when the server gets back to us, whatever's
  specified as request[requestid].onreadystatechange is performed.  So, we have to define .onreadystatechange
  BEFORE we actually make contact with the server.  If you're reading this and trying to learn how it works,
  you may want to take a glance at the last part of the communicate() function first, and then come back here. */
  try {
   /* We use try and catch because Javascript will give an error when we try to access request[requestid].status if the
   server is down or if the user navigates away from the page. */
   if (request[requestid].readyState == 4 && request[requestid].status == 200) {
    window.clearTimeout(timeout[requestid]);
    document.body.style.cursor = 'default';
    /* 4 = The AJAX Request is complete; 200 = The HTTP server found the data we needed and was able to send it to us. */
    eval(request[requestid].responseText);
    } else if (request[requestid].readyState == 4 && request[requestid].status != 200) {
    window.clearTimeout(timeout[requestid]);
    if (failure) eval(failure);
    document.body.style.cursor = 'default';
    alert ('Error ' + request[requestid].status + ':  Server error.  If you entered data, it may or may not have been saved.  Please contact your systems administrator.');
    }
   } catch(e) {
   window.clearTimeout(timeout[requestid]);
   document.body.style.cursor = 'default';
   if (failure) eval(failure);
   alert ('Error:  Unable to communicate with server.  Please contact your systems administrator.  You may want to try again in a few minutes to see if the problem fixes itself. \n\n(Either the server was down, the communication was interrupted, or there was an error in the data sent by the server.)\n' + e + '\n\n' + request[requestid].responseText);
   }
  }
 /* IE would NOT stop caching displaying cached data, so I'm now putting the requestid in the query string so it gets fresh data from the server each time. */
 if (method.toLowerCase() == "post") {
  request[requestid].open( "POST", url + "?randomstring=" + requestid, true );
  request[requestid].setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  request[requestid].send(querystring);
  } else {
  request[requestid].open( "GET", url + "?randomstring=" + requestid + "&" + querystring, true );
  request[requestid].setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  request[requestid].send("");
  }
 /* Timeout after 20 seconds.  No need to call failure or put up an alert because onreadystatechange takes care of that. */
 timeout[requestid] = window.setTimeout("timeout['" + requestid + "'] = request['" + requestid + "'].abort()", 20000);
 }

 

If you would like a reply to your comment, you must leave your email address! We receive dozens of questions every month from people who don't leave us with any way to contact them, so we have no choice but to ignore the question. We try to reply to as many questions as we can, if we know the email address of the person who asked the question. Thanks in advance for writing in :)

Allowed HTML: <b>, <i>, <em>, <strong>. All other < and > will be replaced with &lt; and &gt;.