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;
}
There are quite a few problems with this code. Here are just the first ones I found:
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: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.
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.