How to send multiple ajax requests?

I am new to ajax. I have a function to insert a list of items into sql using a php page, but it only inserts the last item. Please take a look at the code below:

function submitItems() {
    ...
    xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        if (xmlhttp.responseText != "Item Sold")
            alert(xmlhttp.responseText);
        }
    }
    for (i=0;i<rows.length;i++) {//a loop to send multiple requests
        xmlhttp.open("POST","submitItem.php?itemid="+itemid,true);
        xmlhttp.send();
    }
}

The loop sends requests to a php page that does the insertion, but only the last request is processed. If I put an alert() inside the loop, it pops up a window each time, and every item gets inserted, however, it is annoying to keep popping up windows. Any other solutions?

  • History.js replaces the wrong content
  • Why Javascript XMLHttpRequest octet-stream MIME type returns the response as string?
  • Is it possible to abort a synchronous XmlHttpRequest?
  • dojo.store.Observable, JSON REST and queryEngine
  • Not able to pass input value of a form through ajax
  • Refresh Div's content after AJAX form submission
    • Or, as the first reply said, I only send one request with an array that stores a list if items. But I don’t know how to pass an array as parameter. Can I do this?

      var items = new array();
      items.push(itemid);
      .
      .
      .
      .
      items.push(itemid);
      //then just send it?
      xmlhttp.open(“POST”,”submitItem.php?items=”items,true);
      xmlhttp.send();

    and then in the php file, shall I do this?

    $items = $_GET['items'];
    

  • Are MicrosoftAjax.js, MicrosoftMvcAjax.js and MicrosoftMvcValidation.js obsolete as of ASP.NET MVC 3?
  • ajax closest is not affected in ruby on rails
  • What might cause an XMLHttpRequest to never change state in Firefox?
  • ngResource retrive unique ID from POST response after $save()
  • qq.FileUploader doesn't work when loaded in AJAX popup
  • Assigning Code to a specific button
  • One Solution collect form web for “How to send multiple ajax requests?”

    Use the for loop to generate an array of items (push the different itemids into the array on each iteration) and then make only one AJAX call in which you’ll insert all of the items to the database. This way will also optimize your site and save your bandwidth.