PDA

View Full Version : for loop issue!



efc_90
10 Jan 2011, 07:55 AM
--------------------------------------------------------------------------------

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) {

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

JamieD
10 Jan 2011, 06:25 PM
Hi,

Have you considered loading all of your data in one hit? It's pretty expensive in terms of network traffic to make a request for each slip.

If your do_payslips_ajax.php script returned a JSON array of all pay slips for a particular year you could then loop the results and build the view from that.

For example, do_payslips_ajax.php returns:

{
slips: [
{text: "slip text 1"},
{text: "slip text 2"},
{text: "slip text 3"},
{text: "slip text 4"},
{text: "slip text 5"}
]
}

Then if your processing code something like:



var data = JSON.parse( http_request.responseText );
for(var i=0; i<data.slips.length; i++){
document.getElementById("p" + i).innerHTML = data.slips[i].text;
}


You may also want to look at using a library like jQuery (http://jquery.com) which will give you much more robust code and better cross browser support.