1

I have a javascript function that calls an AJAX, like this:

function addSquadronByID(id) {
        $.ajax
        ({
            type: "POST",
            url: "server/get_squadron.php",
            data: {
                'id': id,
                'counter': squadron_counter
            },
            cache: false,
            success: function (data) {
                squadron_counter++;
            },
            error: function () {
                alert("AJAX error.");
            }
        });
    }
}

Outside the document.ready, the variable is initialized like this var squadron_counter = 0;

This function perfectly works while I call it in the page, but if I try to use PHP to write it in the page, like this:

        $list_squadrons = $DB->Execute($query);
        while(!$list_squadrons->EOF){
            $currentSquadron_id = $list_squadrons->fields["squadron_id"];
            $currentSquadron_number = $list_squadrons->fields["squadrons"];
            echo "addSquadronByID($currentSquadron_id);\n";
            $list_squadrons->MoveNext();
        }

The function writes into the document.ready() the correct calls, but squadron_counter is always zero, even if the function works. My only idea is that it works this way because javascript calls all the functions at once and does not wait to complete the first one before executing the second one, etc.. but how do I solve this?

HTML output as requested:

addSquadronByID(3, squadron_counter);
addSquadronByID(5, squadron_counter);
addSquadronByID(6, squadron_counter);

This is put into a

$( document ).ready(function() {
});

inside a <script> tag.

5
  • Please show you html output. It's not clear to where the PHP script outputs. Commented Nov 11, 2015 at 14:06
  • You put the second one in the callback of the first one. Commented Nov 11, 2015 at 14:09
  • Added HTML output as requested Commented Nov 11, 2015 at 14:11
  • why just dont calculate the final value of squadron_counter in php?? Commented Nov 11, 2015 at 14:31
  • When do you check for squadron_counter value? What do you mean by "it works while I call it in the page"? It is correct that JS will send all 3 requests without waiting for any of them to succeed (this is the expected behaviour of asynchronous tasks, as in the first "A" of AJAX). So if you check squadron_counter value just after having sent those 3 requests, you do not give a chance to any of those requests to complete, hence to update the value. Commented Nov 11, 2015 at 15:46

1 Answer 1

1

I think your idea about JS calling all functions without waiting for the first one to complete is in the right direction. This is called "asynchronous requests". Please refer to How to return the response from an asynchronous call? for a detailed explanation.

The idea is to send your 3 requests and then wait for all of them to complete before checking the value of your squadron_counter variable (or whatever data you have updated in your success callbacks).

Then if my understanding is correct, you do not know how to implement this waiting?

Since you are using jQuery, the implementation is super simple. Note first that your jQuery.ajax request returns a Deferred object. So simply keep a reference of the Deferred object created by each AJAX request you send. Then you could use for example jQuery.when with a callback in its then method to wait for all your requests to complete:

function addSquadronByID(id) {
    return jQuery.ajax({ /* ... */ }); // returns a Deferred object.
}

var d1 = addSquadronByID(3),
    d2 = addSquadronByID(5),
    d3 = addSquadronByID(6);

jQuery.when(d1, d2, d3).then(
    // callback executed on success of all passed Deferred objects.
    function () {
        console.log(squadron_counter);
    }
);

Demo: http://jsfiddle.net/btjq7wuf/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.