A SOLID Ajax XMLHttpRequest/ActiveXObject???

Discussion in 'JavaScript' started by abi, Dec 15, 2008.

  1. #1
    Hi guys,

    I'm really starting to get into making ajax/javascript sites now -- they seem to be going well, but i just want a really reliable request object. Right now i use this:

    
    function createRequestObject() {
    	   var objAjax;
    	   var browser = navigator.appName;
    	   if(browser == "Microsoft Internet Explorer"){
    		  objAjax = new ActiveXObject("Microsoft.XMLHTTP");
    	   }else{
    		  objAjax = new XMLHttpRequest();
    	   }
    	   return objAjax;
    }
    var http = createRequestObject();
    
    Code (markup):
    Then send and recive with this:

    
    	function getName(me){
    	   http.open('get', 'https://site.com?a=' + me); 
    	   http.onreadystatechange = gotName;
    	   http.send(null);
    	   return false;
    	}
    
    
    function gotName(){
    		if(http.readyState == 4){
    			var name = http.responseText;
    			// Do what you need to do.
    		}
    }
    
    Code (markup):
    The above works fine, but is there any improvements i can make to the above code? Sometimes when requesting data, it just hangs, and nothing ever turns up. It would be too unreliable as a login for example.




    Also, if you need to get more then one request at once, what is the best thing to do, for example...

    ---- Using the same createRequestObject Function as above ----

    
    	function getName(me){
    	   http.open('get', 'https://site.com?a=' + me); 
    	   http.onreadystatechange = gotNameResult;
    	   http.send(null);
    	   return false;
    	}
    
    	function findName(me){
    	   http.open('get', 'https://site.com/page2.php?a=' + me); 
    	   http.onreadystatechange = FindNameResult;
    	   http.send(null);
    	   return false;
    	}
    
    getName("jack")
    findName("paul")
    
    
    Code (markup):
    Thanks for any help.

    Cheers.
     
    abi, Dec 15, 2008 IP
  2. rene7705

    rene7705 Peon

    Messages:
    233
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    jQuery.com ftw! :)
     
    rene7705, Dec 15, 2008 IP
  3. brownskinman

    brownskinman Peon

    Messages:
    18
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yeah!

    Give it a shot abi - 2 to 3 lines of code will make ya sleep like a baby...

     
    brownskinman, Dec 15, 2008 IP