I have a page that dynamically creates (using jQuery) input fields for a user. The user can then enter values ββin each input field that he created. When the save button is clicked, a javascript function is called, which iterates through all the input windows entered by the user and sends these values ββusing XMLHttpRequest to the process.php file, which inserts these values ββinto the database.
This code works fine if I send only one request at a time. But if I loop it and send a value from each window at each iteration (which means send a few requests using a loop), only the last request will succeed. All other calls except the last call are interrupted (found using firebug).
Any idea why this is happening?
My code is:
<script> function saveTimeSlots(){ var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); } catch(e){ alert('Issue with browser.') } ajaxRequest.onreadystatechange = function(){ if( ajaxRequest.readyState==4 ){ alert(ajaxRequest.responseText); //This returns empty except for last call } } var timeSlots = document.getElementById('formSlots').childNodes; var date = $.datepicker.formatDate('dd-mm-yy', new Date($('#datepicker').datepicker("getDate"))); for(j=0; j<timeSlots.length; ++j){ var time = timeSlots[j].getElementsByTagName("input")[0].value; var status = 1; var queryString = "?date=" + date + "&time=" + time + "&status=" + status; ajaxRequest.open("GET", "process.php" + queryString, true); ajaxRequest.send(null); } } </script> <input type="button" value="Save time slots" class="custom-button" onclick="saveTimeSlots()"/>
Below is the process.php code
<?php mysql_connect( $dbhost,$user,$pwd ); mysql_select_db( $dbase ) or die( mysql_error() ); $date = mysql_real_escape_string( $_GET['date'] ); $time = mysql_real_escape_string( $_GET['time'] ); $status = mysql_real_escape_string( $_GET['status'] ); $query = "INSERT INTO time_slots (`date`,`time`,`status`) VALUES ('" . $date . "','" . $time . "'," . $status . ")"; echo $query; if( mysql_query( $query ) ){ echo "Success"; }else{ echo mysql_error(); } mysql_close(); } ?>
This shows Firebug:
GET http://localhost/process.php?date=24-06-2012&time=1&status=1 Aborted GET http://localhost/process.php?date=24-06-2012&time=2&status=1 Aborted GET http://localhost/process.php?date=24-06-2012&time=3&status=1 200 OK 31ms
source share