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?
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'];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With