views:

412

answers:

2

http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#xmlhttprequest

4 Loaded The data transfer has been completed.

readyState == 4

I used the ajax framework from w3schools.

I want to process the data from a group of rows. (form fields). I loop through the form elements and send them to the ajax script. The ajax script then sends the data via get to a php page that processes the data. Once the processing is complete, the data should then be displayed back to the original page where the function was called.

I get this error message: "The data necessary to complete this operation is not yet available." and results for the last row are displayed only. The function works correctly on an individual bases, but when I try to loop through more than one row that error occurs.

function stateChanged5() 
{ 

    if (request5.readyState==4)
    {
     document.getElementById(displayElem).innerHTML=request5.responseText;
    }
    else
    {
     document.getElementById(displayElem).innerHTML=""; 
    }
}

Ready state condition is breaking to here except for last row. If I try to put the above line of code here I get the the data necessary to complete this operation is not yet available. This is how I came to the conclusion that the php page is not proccessing the data fast enough for the ajax to return it and display it in time for the next iteration.

+1  A: 

Wait for each row's results to come back before kicking off the request for the next one.

moonshadow
How would I go about doing such a thing?
payling
Using recursion. See my answer.
Josh Stodola
A: 

Recursion...

var counter = 0;

function makeRequest() {
  var xhr = // yada yada yada, get your XmlHttpRequest instance
  xhr.onreadystatechange = function() {
    if(this.readyState == 4) {
      // Do whatever, based on the counter variable
      counter += 1
      if(counter < 5)
        makeRequest();
    }
    else {
      // Do whatever, based on the counter variable
    }
  }
  xhr.open();
}
Josh Stodola
make request is passed an element name from a forum. On the original page while loop iterates through array of form elements and passes it to the makerequest function, how would recursion work with the way I have things setup. I can't call the makeRequest again because it'll be the same element won't it?
payling
You need to use the counter variable to figure out which element to use. You'll need to adjust the way you have things setup now (implied - given that it does not work!).
Josh Stodola
If you want an answer more adapted to your setup, then you need to post more code to illustrate it. There are no mind-readers here.
Josh Stodola
thanks, figured it out with the aid of your code.
payling