JQuery $ .post in PHP foreach loop

advertisements

I have a form where a subscriber can select the newsletters they want to recieve and then an AJAX form will send the results to Exact Target and add the subscriber to every list the subscriber want to be added too.

I have a PHP foreach loop setup to handle this.

<?php foreach ($listNumbers as $item): ?>
            var xmlData = 'Ths is the ET API call';
            $.post('ET url for API call'+xmlData);
        <?php endforeach; ?>

After the loop(s) run the user is sent to a thank you page like this.

$(document).ready(function() {
location.href = "thank you url";
});

Everything works.. for the most part. I'm using document ready because I'm wanting to give the loop enough time to submit the API call. Is there a way to detect when the $.post function(s) are complete? If it is sucessfull? and then send the user to thank you page?

I'm finding that the location href is sending some users to the thank you page before the code has a chance to run.

Thanks, Michael


http://api.jquery.com/jQuery.post/

There's a callback that tells you it's finished

jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )

  • url - A string containing the URL to which the request is sent.
  • data - A map or string that is sent to the server with the request.
  • success(data, textStatus, jqXHR) - A callback function that is executed if the request succeeds.
  • dataType - The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

Sample script, you need to keep track that all requests have finished, although I would strongly suggest you write a new server side call that you can call just once, if you can.

var xhrCount = <?= count($listNumbers) ?>;
<?php foreach ($listNumbers as $item): ?>
   var xmlData = 'Ths is the ET API call';
   $.post('ET url for API call'+xmlData, null, function() {
       xhrCount--;
       if (xhrCount === 0) {
           location.href = 'myurl'
       }
   });
<?php endforeach; ?>

Not sure, what could be wrong with your count() but you can count it yourself;

var xhrCount = 0;
<?php foreach ($listNumbers as $item): ?>
   var xmlData = 'Ths is the ET API call';
   xhrCount++;
   $.post('ET url for API call'+xmlData, null, function() {
       xhrCount--;
       if (xhrCount === 0) {
           location.href = 'myurl'
       }
   });
<?php endforeach; ?>