Categories: Snippets

Ajax getHTTPObject function

/*Usage
 * var request = getHTTPObject();
 * if(request){
 * AJAX CODE HERE
 * }
 * 
 * If getHTTPObject returns false, the browser isn't Ajax compatible. The if 
 * statement checks to see if it exists, then runs the code.
 */function getHTTPObject() {
 var xhr = false;//set to false, so if it fails, do nothing
 if(window.XMLHttpRequest) {//detect to see if browser allows this method
  var xhr = new XMLHttpRequest();//set var the new request
 } else if(window.ActiveXObject) {//detect to see if browser allows this method
  try {
   var xhr = new ActiveXObject("Msxml2.XMLHTTP");//try this method first
  } catch(e) {//if it fails move onto the next
   try {
    var xhr = new ActiveXObject("Microsoft.XMLHTTP");//try this method next
   } catch(e) {//if that also fails return false.
    xhr = false;
   }
  }
 }
 return xhr;//return the value of xhr
}
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
// Get file
function grabFile(file) {
  var request = getHTTPObject();
  //GET
  if (request) {
    request.open('GET', file, true);
    request.send(null);
    request.onreadystatechange = function(){
      if (request.readyState != 4) return false;
      if (request.status == 200 || request.status == 304) {
        console.log(request.responseText);
      }
    };
  }
}

 

Share

Recent Posts

Selecting Elements in jQuery (jQuery Selectors)

To collect a group of elements, we pass the selector to the jQuery function using…

5 years ago

jQuery library Introduction

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is…

5 years ago

Adjust li width fit with ul width of the outer div/body

HTML:- [crayon-6637b6416a6c6372016942/] CSS:- [crayon-6637b6416a6cc791635162/] JavaScript:- [crayon-6637b6416a6ce502693613/]  

5 years ago

Customize Input Box using jQuery

Prevent users typing special characters in text box, textarea, etc. [crayon-6637b6416a7e2431708057/] ^[a-zA-Z]+$ Alphabets ^[a-zA-Z\s]+$ Alphabets…

5 years ago

JavaScript simple form validation with example

Any interactive web site has form input - a place where the users input different…

5 years ago

Clear the browser cache of CSS or JavaScript Using Javascript

[crayon-6637b6416aaf9722065830/]  

5 years ago