skip to Main Content

I want to run ajax in every loop of the selected checkbox. However ‘jquery each’ ignores the ajax process. Completed or not completed the loop will continue. Sorry for my language, hope it’s understandable.

Here is an example of the code I made.

$('input[name="options[]"]:checked').each(function() {
  jQuery.ajax({
    url: "www.example.com",
    type: "POST",
    data: {
      name:name
    },
    success: function(data) {
      // do something
    }
  });
});

I have tried using async:false in the ajax option, but the page freezes, and will return to normal after the process is complete.

2

Answers


  1. So all you have to do with any kind of Promise batches is gather all of them to array and pass to "batch Promises" function. No matter if it’s jQuery, Angular or other

    
    // Gather all promises returned from $.ajax
    var allPromises = [];
    
    $('input[name="options[]"]:checked').each(function () {
        allPromises.push(
            callAjax($(this).val()
        );
    });
    
    $.when(allPromises).then(function () {/* do something after all*/})
    
    function callAjax(name) {
        // Returns promise from $.ajax
        return jQuery.ajax({
            url: "www.example.com",
            type: "POST",
            data: {name: name},
            success: function (data) {/* do something after this call*/}
        });
    }
    
    
    Login or Signup to reply.
  2. Here is an alternative solution using fetch(), as it is available in all modern browsers (no jQuery needed):

    const jsrv='https://jsonplaceholder.typicode.com/',
          arr='users,posts,comments'.split(',');
          
    Promise.all(arr.map(e=>fetch(jsrv+e).then(r=>r.json())))
           .then(console.log)
    .as-console-wrapper {max-height:100% !important}

    In this sample script I collect the responses from three Ajax calls to the publicly avaible resource provided by typicode.com: The resulting array then consists of three arrays containing the users, posts and comments. In my demo I simply provide console.log as the processing function. This will of course be different in a real life situation.

    fetch can be used with POST too, see here for more details: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search