Doug
Doug

Reputation: 6477

Two ajax calls in two different divs

What I am trying to do is to make two ajax calls and make each result show up in two different divs of the same page.

Here is my Javascript code:

function firstLoad(){
    firstDiv(datedisplay.value);//populating first div
    secondDiv(datedisplay.value);//populating second div
}

function loadXMLDoc(url,cfunc){
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}
function firstDiv(changed_date){
    var divided_date = changed_date.split("-");
    loadXMLDoc("getmonth.php?m="+divided_date[0]+"&y="+divided_date[1],function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("timetableview").innerHTML=xmlhttp.responseText;
        }
    });
}
function secondDiv(changed_date){
    var divided_date = changed_date.split("-");
        loadXMLDoc("getmonthexp.php?m="+divided_date[0]+"&y="+divided_date[1],function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("expensesview").innerHTML=xmlhttp.responseText;
        }
    });
}

The response content is correct, however what happens now is that: The second div is filled correctly. The first div stays in blank, and if I keep refreshing the page, eventually the content of the second div will show up in the first div as well(weird).

Hope you guys can help me.

Upvotes: 1

Views: 75

Answers (2)

user3913494
user3913494

Reputation:

xmlhttp is global because you don't use the var keyword. This means that the onreadystatechange function you use for one will overwrite the other.

function loadXMLDoc(url, cfunc) {
    var xmlhttp;

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

xmlhttp is global because you don't use the var keyword. This means that the onreadystatechange function you use for one will overwrite the other.

function loadXMLDoc(url, cfunc) {
    var xmlhttp;

Upvotes: 1

Related Questions