How to execute multiple, chained $.post() calls in consecutive order?

拜拜、爱过 提交于 2019-12-21 19:54:31

问题


What I'm Trying To Accomplish

I need to trigger 1 to 3 different $.post() requests, and whether it's 1 call, 2 consecutive calls, or 3 consecutive calls is decided by some basic user selection. Each call must only start after the previous is completely finished.

I am dealing with 3 simple behavior cases -- the user, being presented with "Checkbox 1," "Checkbox 2," and a "Continue" button," opts to

  1. Select nothing and then press "Continue" button, which makes an XHR call to '/remote.php',
  2. The user opts to only select "Checkbox 1" or "Checkbox 2," and then presses "Continue" button, which calls $.post() Function 1 that is bound to Checkbox 1, or $.post() Function 2 that is bound to Checkbox 2, and then makes an XHR call to '/remote.php',
  3. Or the user selects both Checkbox 1 + 2 and then presses Continue, which calls $.post() Function 1, then calls $.post() Function 2, and then makes an XHR call to '/remote.php'.

I need to make sure that the Continue-button $.post() function does not fire until the Checkbox-bound $.post() functions fire and complete.


The Problem

The problem is that if Checkbox 1 is selected and Checkbox 2 is selected, and then the Continue button is pressed, as I understand it, the loading order should be:

  1. Checkbox 1 bound $.post() request fires and completes, then
  2. Checkbox 2 bound $.post() request fires and completes, then
  3. Continue button bound $.post() fires, and pages is changed via AJAX at the end of the function tied to "Continue" button bound function.

So, where the result should look like:

XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/cart.php?action=add&product_id=1284". 
XHR finished loading: POST "/remote.php".

It instead often comes out like this:

XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/remote.php".
XHR finished loading: POST "/cart.php?action=add&product_id=1284". 

So when the page changes due to the AJAX at the end of the "last"/"Continue-button function, either neither of the Checkbox 1 or Checkbox 2 actions have taken place, or one of the two or both do register in the backend (ie, added to cart) but do not reflect in the AJAXified DOM as they should as the final AJAX fires and completes before the previous $.post() calls have completed.


My Code

The HTML

The HTML is basic:

<form method="post" action="#" onsubmit="newChooseShippingProvider(); return false;">
    <label for="delSigCheck" class="del-sig-text"><input id="delSigCheck" type="checkbox" onchange="addDelSigToCart();" title="Add Delivery Signature"></label>
    <label for="addInsCheck" class="ins-add-calc"><input id="addInsCheck" type="checkbox" onchange="addInsToCart();" title="Add Delivery Signature" data-ins-id="1284"></label>
    <input type="submit" value="Continue" class="btn Small">
</form>

The Javascript/jQuery

This is my latest--4th or 5th--attempt, and still does not work:

function addDelSigToCart() {
    $('#delSigCheck').toggleClass('checked');
}
function addInsToCart() {
    $('#addInsCheck').toggleClass('checked');
}
function newChooseShippingProvider() {
    var originalCheckout = ExpressCheckout.ChooseShippingProvider();
    if ($('.ShippingProviderList .radio span').hasClass('checked')) {
        var addInsCheck = $('#addInsCheck').hasClass('checked');
        var delSigCheck = $('#delSigCheck').hasClass('checked');
        var insId = $('#addInsCheck').attr('data-ins-id');
        var addDelSigUrl = '/cart.php?action=add&product_id=1280';
        var addInsUrl = '/cart.php?action=add&product_id=' + insId;
        if (delSigCheck && addInsCheck) {
            $.post(addDelSigUrl, function() {
                $.post(addInsUrl, function() {
                    originalCheckout;
                });
            });
        } else if (!delSigCheck && !addInsCheck) {
            originalCheckout;
        } else if (delSigCheck && !addInsCheck) {
            $.post(addDelSigUrl, function() {
                originalCheckout;
            });
        } else if (!delSigCheck && addInsCheck) {
            $.post(addInsUrl, function() {
                originalCheckout;
            });
        }
    } else {
        originalCheckout;
    }

What I've Tried

I've gone through several version of chaining the $.post() calls, but nothing seems to work consistently.

What I am using now and what seems to work the best for me with extensive testing is using setTimeout to chain the function with some delay, like this:

    ...
    if (delSigCheck && addInsCheck) {
        $.post(addDelSigUrl);
        setTimeout(function() {
            $.post(addInsUrl);
            setTimeout(function() {
                ExpressCheckout.ChooseShippingProvider();
            }, 1300);
        }, 1300);
    } else if ...

And this version above is what I'm using now, as it seems to give the most consistent results, seeing the scripts load typically as 1,2,3, followed by a DOM AJAXified with appropriate changes based on function 1 and 2. However, I don't think the setTimeout is working as even when I increase it to 5000 or 10000, the action is performed "instantaneously" and no delay takes place (at least certainly nothing close to 5-10 seconds).

I've also tried putting the functions inside $.post()'s success callback:

    ...
    if (delSigCheck && addInsCheck) {
        $.post(addDelSigUrl, function() {
            setTimeout(function() {
                $.post(addInsUrl, function() {
                    setTimeout(function() {
                        originalCheckout;
                    }, 1300);
                });
            }, 1300);
        });
    } else if ...

And finally I've also tried:

$.when($.post(addDelSigUrl)).then(originalCheckout);

as well as .done and success: but none of it works, and the $.posts()'s load in an unexpected order, failing.

The Question

  1. What am I doing wrong?
  2. How can I make it so 1 loads fully, then 2 loads fully, and only then 3 fires and loads?

UPDATE 1:

I just tried jfriend00's answer:

            $.post(addDelSigUrl, { cache: false }).then(function(data1) {
                //CONSOLE.LOGing HERE
                console.log(data1);
                return $.post(addInsUrl, { cache: false });
            }).then(function(data2) {
                //CONSOLE.LOGing HERE
                console.log(data2);
                return originalCheckout;
            });

But it still resulted in:

XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/remote.php".
XHR finished loading: POST "/cart.php?action=add&product_id=1284". 

and both console.logs fire immediately after the first "XHR ...", THEN /remote.php fires (though it should fire last as part of originalCheckout), THEN the 3rd XHR fires.

UPDATE 2

Now that we got the XHRs firing and loading in the correct order via .then(), the second part of the problem I am having is that the 3rd XHR to /remote.php updates the DOM via AJAX with data from the backend. Part of that data is the 1st and 2nd $.posts.

I think the 3rd AJAX call is firing and completing milliseconds before some action is taken on the backend via server-side PHP, and because of this more than 50% of the time, the DOM update via the 3rd AJAX call is missing the data from the 1st and/or 2nd call (most often the DOM changes include Checkbox 1/AJAX call 1, but not 2).

How can I fix this? I've tried setTimeout but it doesn't seem to work as even when I set it to like 30000, the 3rd AJAX fires as soon as the 1st/2nd complete.

Latest front-end code:

function newChooseShippingProvider() {
    if ($('.ShippingProviderList .radio span').hasClass('checked')) {
        var addInsCheck = $('#addInsCheck').hasClass('checked');
        var delSigCheck = $('#delSigCheck').hasClass('checked');
        var insId = $('#addInsCheck').attr('data-ins-id');
        var addDelSigUrl = '/cart.php?action=add&product_id=1280';
        var addInsUrl = '/cart.php?action=add&product_id=' + insId;
        if (delSigCheck && addInsCheck) {
            $.post(addDelSigUrl).then(function(data1) {
                return $.post(addInsUrl);
            }).then(function(data2) {
                return ExpressCheckout.ChooseShippingProvider();
            });
        } else if (!delSigCheck && !addInsCheck) {
            ExpressCheckout.ChooseShippingProvider();
        } else if (delSigCheck && !addInsCheck) {
            $.post(addDelSigUrl).then(function(data1) {
                return ExpressCheckout.ChooseShippingProvider();
            });
        } else if (!delSigCheck && addInsCheck) {
            $.post(addInsUrl).then(function(data1) {
                return ExpressCheckout.ChooseShippingProvider();
            });
        }
    } else {
        ExpressCheckout.ChooseShippingProvider();
    }
}

回答1:


The simplest way to sequence jQuery ajax operations is to use the built-in promises:

$.post(...).then(function(data1) {
    return $.post(...);
}).then(function(data2) {
    return $.post(...);
}).then(function(data3) {
    // everything done here
});

Working demo that shows you the precise sequencing: http://jsfiddle.net/jfriend00/zcfr2xy0/


OK, it appears that the problem is that you're doing this:

var originalCheckout = ExpressCheckout.ChooseShippingProvider();

And, then you think that sometime later, you can just do:

originalCheckout;

and that will somehow execute the former. That's not the case. Your ExpressCheckout.ChooseShippingProvider() function is executed immediately and the return result from executing that function is assigned to originalCheckout.

You simply can't do it that way. When you have () after a function name, that means to execute it NOW. I would suggest that you just replace all instances of originalCheckout; with ExpressCheckout.ChooseShippingProvider();.




回答2:


If you "chain" AJAX post operations (meaning that you do your process once receiving the data from the previous call) then nothing strange should happen.

From the symptom I'd think more to some cache-related problem. Adding an extra random value to the query is a quick'n dirty way to get rid of whoever is caching the result and responding instead of who should. Also using a POST request instead of a GET (if possible) may help on this issue and better conveys the idea that the operation is a mutation that should not be skipped or done out of order.

Note that a stale response problem could be at several levels: browser, proxy, web server, cms plugin...



来源:https://stackoverflow.com/questions/32160546/how-to-execute-multiple-chained-post-calls-in-consecutive-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!