Results 1 to 2 of 2

Thread: for loop issue!

  1. #1
    efc_90 Guest

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

    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

  2. #2
    Join Date
    May 2006
    Posts
    4
    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:
    Code:
    {
      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:

    Code:
    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 which will give you much more robust code and better cross browser support.

Similar Threads

  1. two records from the same table in for loop
    By catalepticstate in forum Client & Server Side Scripting (PHP, ASP, JavaScript)
    Replies: 0
    Last Post: 11 Oct 2010, 04:26 AM
  2. How do I loop a video using HTML?
    By brynjarh in forum Web Design, HTML Reference and CSS
    Replies: 1
    Last Post: 29 Jan 2008, 09:53 AM

Posting Permissions

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