DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Basic XMLHttprequest

03.25.2008
| 5647 views |
  • submit to reddit
        Non-IE version:

xhr = new XMLHttpRequest();                     
xhr.open(
    "GET",                          
    "http://foo.com",       
    true                            
  );
xhr.onreadystatechange=function(){
    if (xhr.readyState==4){
      if (xhr.status==200){
        parseResponse(xhr);
      }else{
        //handle the HTTP error...
      }
    };
  };
xhr.send(null); 

// Basic XMLHttprequest (code from http://www.sitepoint.com/article/take-command-ajax)

function makeHttpRequest(url){

   var http_request = false;

   if (window.XMLHttpRequest) { // Mozilla, Safari,...
   
       http_request = new XMLHttpRequest();
	   
       if (http_request.overrideMimeType){
	   
           http_request.overrideMimeType('text/xml');
		   
       }
	   
   } 
   else if (window.ActiveXObject) { // IE
   
       try{
	   
           http_request = new ActiveXObject("Msxml2.XMLHTTP");
		   
       } 
	   catch(e){
	   
           try{
		   
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
			   
           } 
		   catch (e) {}
       }
	   
   }

   if (!http_request) {
   
       alert('Unfortunatelly you browser doesn\'t support this feature.');
	   
       return false;
	   
   }
   http_request.onreadystatechange = function() {
   
       if (http_request.readyState == 4){
	   
           if (http_request.status == 200){

				alert(http_request.responseText);

           } 
		   else{
		   
               alert('There was a problem with the request.(Code: ' + http_request.status + ')');
			   
           }
		   
       }
	   
   };
   
   http_request.open('GET', url, true);
   http_request.send(null);
}