/    Sign up×
Community /Pin to ProfileBookmark

For loop / ajax issue

Hi all,

I have a problem where I’m trying to load data into multiple divs. They are payslips, so p1, goes into january, p2 into febuary etc. I want to onLoad them all so when the page is loaded they are all displayed.

Every time I try this, the loop automatically goes to the last iteration, 6 in this example, so the only div that is loaded is p6.

Here is my code:

function replace(slip, year) { // table contains either ‘bank’ or ‘intranet’

xmlHttpReq.open(“POST”, “do_payslips_ajax.php”, true);
xmlHttpReq.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
xmlHttpReq.onreadystatechange=function() {

if(xmlHttpReq.readyState == 4) {

document.getElementById(“p” + slip).innerHTML = xmlHttpReq.responseText;

}
}

xmlHttpReq.send(getquery(slip,year));

}

function getquery(slip,year) {

strQuery = “weekmonth=” + slip + “.” + year;
return strQuery;

}

function loadpayslips(year) {

for (slip=1; slip<=6; slip++) {

replace(slip, year);

}

}

<label>
<body onload = loadpayslips(11)> search</a> &nbsp;&nbsp;
</label>

<div id=”p1″>
/div>

<div id=”p2″>
month 2</div>

<div id=”p3″>
month 5</div>

etc..

Any help would be appreciated.
Thanks

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@cluefulJan 10.2011 — You're using a global request object that is being overwritten on each iteration of the loop. Assign the request to a local variable:
[CODE]function replace(slip, year)
{

[B]var xmlHttpReq = getRequest(); /* Or whatever your function is called */[/B]

xmlHttpReq.open("POST", "do_payslips_ajax.php", true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded');
xmlHttpReq.onreadystatechange=function() {

if( this.readyState == 4) {

document.getElementById("p" + slip).innerHTML = this.responseText;

}
}

xmlHttpReq.send(getquery(slip,year));

}
[/CODE]
×

Success!

Help @efc_90 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...