Simple AJAX Example
2008-10-16 13:10:38
Category: javascript:ajax
Description: Use XMLHttpRequest or ActiveX equivalent to create an xml request object. Request a single page and alert the results to the browser.
Author: detour
Viewed: 2009
Rating: (21 votes)


<html>
<head></head>
 
<body>
<script language="javascript">
var xmlhttp = false;
 
// If XMLHttpRequest function does not exist (certain versions of IE, 
// or if native XMLHTTP support is disabled under the security settings),
// create it to return the activex equivalent.
if(!window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    // For maximum compatibility, try all versions.
    var xml_versions=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0",
                      "MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
    for(var x = 0;x < xml_versions.length; x++) {
      try {
        return new ActiveXObject(xml_versions[x]);
      } catch (e) {}
    }
    return false;
  }
}
 
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  try {
    xmlhttp = new XMLHttpRequest();
  } catch (e) {
    xmlhttp = false;
  }
}
 
if(xmlhttp) {
  /* .readyState = 0 Uninitialized
     .readyState = 1 open() Called
     .readyState = 2 send() Called
     .readyState = 3 recieving data, .responseText holds partial data in FF
     .readyState = 4 data finished */
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4) {
      alert("RESPONSE HEADERS:\n\n" + xmlhttp.getAllResponseHeaders());
      alert("STATUS:\n\n" + xmlhttp.status);
      alert("RESPONSE TEXT:\n\n" + xmlhttp.responseText);
    }
  }
 
  xmlhttp.open("GET", "/?var1=val1&var2=val2");
  xmlhttp.send(null);
 
  /* If you want to POST data to recieve_data.php instead
  var post_data = 'var1=' + encodeURIComponent('asj$@#&&?') + '&var2=val2';
  xmlhttp.open("POST", "recieve_data.php");
  xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xmlhttp.setRequestHeader('Content-length', post_data.length);
  xmlhttp.send(post_data); */
}
</script>
 
</body>
</html>