views:

87

answers:

2

I have two divisions, <div id=statuslist></div><div id=customerlist></div>

The function sendReq() creates a xmlhttprequest and fetches the data into the division.

sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');

sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');

I have a problem,

The data fetched into the 'customerlist' gets copied onto 'statuslist'

If i change the order of function calls,

sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');

sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');

Now the data of 'statuslist' gets into 'customerlist'..

Whats the problem with the code?

A: 

I have had this before.

Basically you have a scope problem - you have something like this in your sendReq() function?

if (window.ActiveXObject)
{
 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
 xmlhttp = new XMLHttpRequest();
} 

And so when you make a second request, the xmlhttp object is over-ridden

You need to create a closure where your xmlhttp objects don't clash

eg

function sendReq(url, callbackFunction)
{
    var xmlhttp

    if (window.ActiveXObject)
    {
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
     xmlhttp = new XMLHttpRequest();
    } 

    ...  probably some other stuff here, setting url etc ...

    xmlhttp.onreadystatechange = function()
    {
       if (xmlhttp.readyState==4&&xmlhttp.status='200')
       {
        if (callbackFunction) callbackFunction(xmlhttp.responseText);
       }
    }

    .. probably more stuff here  ( including xmlhttp.send() ) !! ...

}

you can then pass the callback function as a parameter and when the data is successfully loaded, it will be passed to the callback function. Note that you will need to pass the actual function, not just its name (so no quotes around the function name)

Alternatively, you could do what i do which is just use jQuery - works for most of my js problems ;)

Hope this helps

Addsy
A: 

Your sendReq function probably creates one XHR object and re-uses it on second call.

Edit ----

See if this function works as-is:

function sendReq(divId, url, whatEver) {
    var xmlhttp;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP");
            } catch (e) {
                return false;
            }
        }
    }
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == "200") {
            document.getElementById(divId).innerHTML = this.responseText;
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
}
Salman A
I tried creating two objects. But problem still persists.
blacktooth
I'd like to see the code for the `sendReq` function.
Salman A