Home > Software engineering >  Ajax calls by clicking on checkbox - wrong executing
Ajax calls by clicking on checkbox - wrong executing

Time:10-12

I have a page with lots of checkboxes, something like:

<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
<input type="checkbox" value="4">
<input type="checkbox" value="5">
<input type="checkbox" value="6">
<input type="checkbox" value="7">

Also, there are two important numbers:

<h2 id="total-1">100</h2>
<h2 id="total-2">200</h2>

After user clicks on checkbox - i have to send ajax request to server with checkbox value. Server does some logic and sends response with new "total-1", "total-2" numbers. I have to change checkbox background color depends on this numbers and change numbers too.

Here is the problem: There can bee in about 20 checkboxes per page and if user clicks too fast, i have a problem with right values because of async ajax calls.

For example, if user unchecks all checkboxes, numbers should be "0". I clicked fast and received this behaviour:

Total-1     Total-2
100         100      -> If all checkboxes are checked - numbers are same
72          30       -> Some logic, not matter what exactly
50          0        -> all checkboxes unchecked, but number is wrong. 

If i reload the page, i can see that one of the checkboxes is still checked... As is see, the problem with async calls. I need help to understand how to ensure that ajax sends calls in right order. Now, i just set "async" option to "false", but it makes delay after click on input

My idea is to count all requests, save them to global array and check if this response is next in order.

CodePudding user response:

You can implement a queue so that 1 request is implemented at a time,

myQueue.pushRequest(function() {
  return $.ajax({
    ...
  })
});

$(function () {
  var myQueue = {
    queueReq: [],
    pushRequest: function (request) {
      this.queueReq.push(request);
      if (this.queueReq.length === 1) {
        this.executeIncrement();
      }
    },
    clearQueue: function () {
      this.queueReq = [];
    },
    executeIncrement: function () {
      var queueReq = this.queueReq;
      queueReq[0]().then(function (data) {
        queueReq.shift();
        if (queueReq.length) {
            myQueue.executeIncrement();
        }
      });
    }
  };
  • Related