user500468
user500468

Reputation: 1221

Multiple ajax requests

I'm making multiple ajax request by encapsulate in a for-loop:

for(var o = 1; o <= 2; o++)
                {
                    $.ajax({
                        type: 'GET',
                        url: 'lib/terrain.php',
                        dataType: 'html',
                        data: {o: o},
                        success: function(data) {
                            var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
                            angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
                            console.log(data);
                        },
                        error: function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
                    });
                    k=o;                
                } 

This get's information about different objects from my backend:

if(isset($_GET['o']))
{
    $object_query = mysql_query("SELECT * FROM objects");
    $objects = array();
    while($object_row = mysql_fetch_row($object_query))
    {
        $objects[] = $object_row;   //Information about objects
    }

    $count_objects = count($objects);   //Count how many objects it is
    $slump_objects = rand(1, $count_objects);   //Sell of which objects that shoul be viewd at the map.

    var_dump($objects[$slump_objects]);
}

As you can see, I'm making the ajax-call to my backend twice. The problem I have is that sometimes it only get ONE value from my backend, instead of two. Sometimes it get's both the values, which is correct. BUt the problem is that sometimes it only get's one value, and the other value is NULL.

Why is that?

Upvotes: 1

Views: 215

Answers (4)

Steve
Steve

Reputation: 20469

As ajax is asynchronous, your loop will complete immediately, instead you should make your ajax function recursive, calling its self from the done callback:

function doAjax(){
    var total = 2;
    var counter = 0;

    function recursiveAjax(){

        $.ajax({
            //...
            done:function(){
                counter++;
                //call again
                if(counter < total) recursiveAjax();
            }
        });
    }

    //call the first time
    recursiveAjax();
}

Upvotes: 2

Rimas
Rimas

Reputation: 6024

The error is in your PHP code:

$slump_objects = rand(1, $count_objects);   //Sell of which objects that shoul be viewd at the map.

var_dump($objects[$slump_objects]);

If $slump_objects gets value equal to $count_objects (array size) then var_dump($objects[$slump_objects]) returns NULL.

PHP Array starts at index 0, and last index is ($count_objects-1), so change one of statements to:

 $slump_objects = rand(0, $count_objects-1);

or

 var_dump($objects[$slump_objects-1]);

Upvotes: 0

Tapaswi Panda
Tapaswi Panda

Reputation: 1051

Here you are making asynchronous calls means your loop does wait for the first call to be complete before doing the second. And some browsers ignores parallel Ajax call to the exact same url. So you can try changing the url by just appending the value of your loop count.

for(var o = 1; o <= 2; o++)
{
    $.ajax({
        type: 'GET',
        url: 'lib/terrain.php?count='+o,
        dataType: 'html',
        data: {o: 1},
    }).done(function(data) {
        var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
        angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
        console.log(data);    
    }).fail(function() {
        function(xhr, ajaxOptions, thrownError) { alert('Error:'+thrownError); }
    });
}

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34426

Here is an example of using done() to make the second call - http://api.jquery.com/jquery.ajax/

$.ajax({
    type: 'GET',
    url: 'lib/terrain.php',
    dataType: 'html',
    data: {o: 1},
}).done(function(data) {
    var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
    angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
    console.log(data);
    $.ajax({
        type: 'GET',
        url: 'lib/terrain.php',
        dataType: 'html',
        data: {o: 2},
    }).done(function(data) {
        var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
        angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
        console.log(data);
    }).fail(function() {
        function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
    })
}).fail(function() {
    function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
});

Of course this could be done a lot more neatly, this is just to give you an idea of the technique.

Upvotes: 0

Related Questions