Jquery is waiting for $ .each to finish

Hi, I have a huge problem that has been listening to me for a long time, in most cases I could have avoided it, but now there is no other way. Below is a function that, when executed, sends an email request for each checked field. I need him to wait for $ .each to complete to refresh the page. I ran tests with location.reload in the callback of each and for each of them. Of the 10 selected fields, only 7-8 are processed with a reload in the $ .each callback and 3-4 if they move after $ .each (still inside .click). I need him to somehow wait for $ .each to finish and then refresh the page. Is there any way to do this?

$('button.moveToTable').click(function(event){
            $("input:checked").each(function(){
                $.post('/table/move-to-table',
                {orderID: $(this).val(),
                    tableID: $('#moveToTableID').val()
                },
                function(data){
                    location.reload();
                });
            });
            //location.reload();
        });
+5
3

- . , . , - , , , window.Remaining. .

window.Remaining = 0;
$('button.moveToTable').click(function(event){
    window.Remaining = $("input:checked").length;
    $("input:checked").each(function(){
        $.post('/table/move-to-table',
        {orderID: $(this).val(),
            tableID: $('#moveToTableID').val()
        },
        function(data){
            --window.Remaining;
            if (window.Remaining == 0)
                window.location.reload();
        });
    });
    //location.reload();
});
+6

, , , , , .

, , reload() .

- :

var count = 0;

$('button.moveToTable').click(function(event){
            $("input:checked").each(function() { 
                count++; // Increment the counter for each request

                $.post('/table/move-to-table',
                {orderID: $(this).val(),
                    tableID: $('#moveToTableID').val()
                },
                function(data) { 
                    count--; // Decrement as the requests return

                        // Only reload if the count is 0
                    if( count === 0 )
                        location.reload();
                });
            });
        });

, , click . , count.

:

if( count === 0 ) { 
    $("input:checked").each(func...

nsw1475 , .

+5

A better, more efficient and easier way to do this could be to use the each () function to generate a json array to store the checkboxes for, and then use .post to transfer all your data together. After that, go to the page refresh page.

+2
source

All Articles