简体   繁体   中英

How to check multiple $.post has been send and result has been fetched on the page

In my javascript code when someone change option and click on Go. it's change property for multiple items. I see the save button and edit button for every item.

so I manually clicked the button after change the select and on the click of Go.

for (var i = 0; i < checked.length; i++) {
        var cur = checked[i];
        $(cur).parents('tr').find('.transaction-category-wrapper .select2').val(catId);
        $(cur).parents('tr').find('.transaction-verify-wrapper .btn-save').click();
    }

Now problem is I want to refresh the page, but after making sure that response has been come to the page. How I can achieve it.

I am thinking to implement the setTimeout but it wouldn't be good option in case of server doesn't has executed and timeout just refresh the page.

Is jQuery have some property which let me know that javascript request has been complete and response has been received.

$(document).on('click', '.btn-save', function () {
                 // val logic

                $.post("/Entries/AddEntries", val, function (r) {
                    enableTooltip();
                });
            });

You can use .then to handle success and failure cases of your AJAX requests:

$.post("your_url", { ... })
  .then(function() {
    // If succeeded
  }, function() {
    // If failed
  });

.post returns a jQuery deferred object, which can be responded with a .then() handler. The first argument of .then is considered as a success handler, and the second one is a failure handler.

In case of multiple AJAX calls, you can use $.when to take action when all the AJAX calls are done.

$.when($.post( ... ), $.post( ... ))
  .then(function() {
    // If all AJAX calls succeed
  }, function() {
    // If any of the call fails
  });

Since every click generates a post request. You need to keep track of all those requests in an array and then wait for them to resolve. So, your code should look like:

var requests = [];
$(document).on('click', '.btn-save', function () {
             // val logic
            requests.push($.post("/Entries/AddEntries"));
        });
Promise.all(requests).then((data) => {do something});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM