SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    AJAX: Can't make multiple httprequests

    Here is my JavaScript:
    Code:
    var xmlHttp = createXmlHttpRequestObject(); 
    var newads = "booking.php?action=newads";
    var proofs = "booking.php?action=proofs";
    var updateInterval = 5;
    var errorRetryInterval = 30; 
    var debugMode = true; 
    
    function createXmlHttpRequestObject() { 
    	var xmlHttp; 
     	try { xmlHttp = new XMLHttpRequest(); } 
      	catch(e) { 
    		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
    		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) { 
    			try { xmlHttp = new ActiveXObject(XmlHttpVersions[i]); }  
    			catch (e) {}
    		} 
        } 
      	if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); 
     	else return xmlHttp; 
    }
    
    function display($newAds) { 
    	newAdsDiv = document.getElementById("newAds"); 
    	newAdsDiv.innerHTML = $newAds + "<br/>"; 
    }
    
    function displayError($newAds) { 
    	display("Error retrieving the news message! Will retry in " + errorRetryInterval + " seconds." + (debugMode ? "<br/>" + $newAds : "")); 
    	setTimeout("process($newAds);", errorRetryInterval * 1000); 
    } 
     
    function process($newAds) { 
    	if (xmlHttp) {
    		try { 
    			xmlHttp.open("GET", newads, true); 
    			xmlHttp.onreadystatechange = handleNewAds; 
    			xmlHttp.send(null);
    		} 
    	catch(e) { displayError(e.toString()); } 
    	}
    }
    
    function handleNewAds() {
    	if (xmlHttp.readyState == 4) {
    		if (xmlHttp.status == 200) {
    			try { getNewAds(); }
    			catch(e) { displayError(e.toString()); }
    		} else { displayError(xmlHttp.statusText); }
    	}
    }
    
    function getNewAds() { 
    	var response = xmlHttp.responseText; 
    	if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0 || response.length == 0) 
        throw(response.length == 0 ? "Server error." : response); 
    	display(response); 
    	setTimeout("process($newAds);", updateInterval * 1000); 
    }
    It works perfectly fine. It goes to booking.php?action=newads and displays the results in a div called "newAdsDiv" in index.html and retrieves every 5 seconds. Exactly what I wanted.

    But now I want to get results from booking.php?action=proofs and display the results in a div called "proofsDiv". I tried to just copy and paste everything after the createXmlHttpRequestObject function and changing everything (including xmlHttp.open) to reflect 'proofs'. All that did was just show the data from proofs and not from newads.

    Any ideas?

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First of all, remove the $'s from the function parameters. Javascript does not use them.

    This could be causing the problem as some places are using the $ when reading where as some are not.


  3. #3
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the quick response.

    When I remove all the $newAds from the function parameters, the script stops working. If I keep the $newAds in just function display(), it will work. I'm not sure why that is.

  4. #4
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Looking at your code, you are using ajax in the wrong way. Really you should only use ajax to return XML, and then use javascript to handle the returned XML Document.

    For every ajax call, I create a new request.

    Something i'd use:

    Code:
    function adHandler(timer) {
    
        var me = this;
        var timer = timer;
        this.createXMLHttpRequest = function() {
            if (typeof XMLHttpRequest != "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject != "undefined") {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                throw new Error("XMLHttpRequest not supported");
            }
        }
        this.doRequest = function(url, callback, postAttributes) {
            var request = createXMLHttpRequest();
            request.open(((postAttributes) ? 'POST' : 'GET'), url, true);
            if(postAttributes) {
                var postStr = '';
                if(typeof(postAttributes) != 'string') {
                    for(var i in postAttributes) {
                        postStr += '&' + i + '=' + postAttributes[i];
                    }
                } else
                    postStr = postAttributes;
                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                request.setRequestHeader("Content-length", postStr.length);
                request.setRequestHeader("Connection", "close");
            }
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    if(request.status == 200) {
                        callback(request);
                    } else {
                        alert('An error has occurred');
                    }
                }
            }
            if(postStr)
                request.send(postStr);
            else
                request.send(null);
        }
        this.getAds = function() {
    
            me.doRequest('http://www.domain.com/booking.php?action=newads', function(res) {
                if(!res.responseXML) {
                    // usuall means an PHP Error has occurred!
                    alert(res.responseText);
                    return;
                }
    
                var doc = res.responseXML.documentElement;
                
                //Handle XML Document which contains information required.
    
                //Sample XML Document
                /*
    
                    <?xml version="1.0" encoding="UTF-8"?>
                    <getAdsResponse time="2008-02-18T08:55:00">
                        <ad id="1" url="http://www.domain.com/ads.php?ad=1" title="Buy something from ebay" />
                        <ad id="2" url="http://www.domain.com/ads.php?ad=2" title="Buy something from amazon" />
                        <ad id="3" url="http://www.domain.com/ads.php?ad=3" title="Buy something from Sitepoint" />
                    </getAdsResponse>
    
                */
    
                var ads = doc.getElementsByTagName('ad');
                
                alert(ads.length); // based on example should return 3
                
                if(ads.length == 0)
                    alert('You have no ads');
                else {
                    for(var i = 0; i < ads.length; i++) {
                        alert('Title: ' + ads[i].getAttribute('title') + '\nID: ' + ads[i].getAttribute('id') + '\nURL: ' + ads[i].getAttribute('url'));
                        // based on ad id 1 of example, you should see
                        /*
                            Title: Buy something from ebay
                            ID: 1
                            URL: http://www.domain.com/ads.php?ad=1
                        */
                    }
                }
    
                // wait specified time and go again.
                setTimeout(me.getAds, me.timer*1000);
    
            });
    
        }
    
    }
    and then to call it

    Code:
    var adHandler = new adHandler(5); // 5 seconds
        adHandler.getAds();
    As the code above is set to call every 5 seconds (or what ever you chose to set) you should call this on your page load. If you want to call it seperately, you'd have to make some minor adjustments.


  5. #5
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HI Guys,

    I'm trying to do something similar myself.

    Im using the following two scripts to call two separate pages into one page, but only one will work at anyone time. I'm new to this so any pointers would be much appreciated on how to get both to work together!

    Code:
    <script language="javascript">
    var xmlHttp
    
    function showTellafriend(str)
    {
    if (str.length==0)
    { 
    document.getElementById("tellafriend").innerHTML=""
    return
    }
    
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
    return
    } 
    var url="shoptellafriend.asp"
    url=url+"?id="+str
    url=url+"&sid="+Math.random()
    xmlHttp.onreadystatechange=stateChanged 
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
    } 
    
    function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
    document.getElementById("tellafriend").innerHTML=xmlHttp.responseText 
    } 
    } 
    
    function GetXmlHttpObject()
    { 
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
    objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
    } 
    
    showTellafriend("[catalogid]")
    </script>

    Code:
    <script language="javascript">
    var xmlHttp
    
    function showReview(str)
    {
    if (str.length==0)
    { 
    document.getElementById("review").innerHTML=""
    return
    }
    
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
    return
    } 
    var url="shopreviewlist.asp"
    url=url+"?id="+str
    url=url+"&sid="+Math.random()
    xmlHttp.onreadystatechange=stateChanged 
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
    } 
    
    function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
    document.getElementById("review").innerHTML=xmlHttp.responseText 
    } 
    } 
    
    function GetXmlHttpObject()
    { 
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
    objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
    } 
    
    showReview("[catalogid]")
    </script>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •