Ivin
Ivin

Reputation: 4815

When sending multiple XMLHttpRequests only the last request returns success

I have a page that dynamically creates (using jQuery) Input boxes for the user. The user can then enter values in each input box he created. On clicking the save button a call is made to a javascript function that iterates through all the input boxes user created and sends these values using an XMLHttpRequest to the process.php file which inserts these values into the DB.

This code works fine if i send only one Request at a time. But if i loop it and send the value from each box on each iteration (means, send multiple requests using loop), only the last Request finds success. All the other calls except the last call gets aborted (found it using firebug).

Any idea why is this happening?

My code:

<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()"/>

Following is the code of process.php

<?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 is what Firebug shows:

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

Upvotes: 4

Views: 5597

Answers (2)

Rob W
Rob W

Reputation: 348972

You cannot use an instance of XMLHttpRequest for more than one request. Create a new instance for each request.

Since you're already using jQuery, I recommend to use $.ajax (or $.get) to fetch the request.

function saveTimeSlots(){
    $('#formSlots').children().each(function() {
        var time = $(this).find('input:first').val();
        var status = 1;
        var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
        $.get("process.php" + querystring, function(responseText) {
            alert(responseText);
        });
    });
}

Upvotes: 6

Esailija
Esailija

Reputation: 140210

You are using the same XMLHttpRequest object for all the requests, so as soon as you start the request, the next one starts another request on it which aborts the previous one.

Make a new XMLHttpRequest object for each request or just use jQuery's ajax. It's not good to have jQuery and not use it.

Upvotes: 6

Related Questions