0

I am trying to save an array of records into a mysql database but I always get the abort message in firebug except for the last save. How do I save the records using a loop for XMLHttpRequest? Here is my code:

function savingContent()
{
   if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();

   }
   else
   {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

   var rowindex = 0;

   for (x in globalObj.AddedRows)
   {
      var rowData = "?q=" + globalObj.AddedRows[rowindex];

      xmlhttp.open("POST", "insertRowData.php"+rowData, true);
      xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
      xmlhttp.setRequestHeader("Content-Length",rowData.length); 
      xmlhttp.send(null);
      rowindex += 1;
}
1
  • If you appreciate the help, please upvote any of the answers you think are helpful, and accept your favorite. Otherwise people won't bother to answer your questions in the future. Commented Jun 16, 2010 at 17:34

2 Answers 2

3

There are quite a few problems with this code. Here are just the first ones I found:

  1. The for (x in object) syntax should only be used when you want to iterate over all fields in an object. In this case you want to iterate over an array, so you should do it like this:

    for (var rowindex = 0; rowindex < globalObj.AddedRows.length; rowindex++) {
    }
    
  2. When doing an HTTP POST, you shouldn't put the data you want to change into the URL. Put it in the body of the request - as the argument to xmlhttp.send(). You're actually explicitly passing a content length - that length is supposed to be the length of the data you pass to xmlhttp.send() - so by passing NULL this is almost certainly your main error.

  3. Rather than using Firebug, it'd be better to use xmlhttp.onreadystatechange to figure out which of your requests are succeeding or failing. Don't assume that once you have it debugged the first time, it will always succeed from then on. Handle errors.

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to dmazzoni:

Every time your for loop sends an async xml request it overrides the previous request and therefore the previous one is aborted. You should create a new XMLHttpRequest (or ActiveXObject for IE) inside your for-loop or wait for the HTTP return call, before sending a new request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.