-1

I want to make an AJAX call when the user clicks on a checkbox. The call sends an id along with the checkbox state. Right now when I click my checkbox it creates two AJAX calls, one with the first id in the list and one is correct one I clicked.

How can I send one ajax call of the checkbox I clicked?

I have hundreds of rows with customer id 1000, 1001, 1002 etc. Right now the AJAX call is always 1000 and an ajax call with the customer id I clicked. Lets say I click the checkbox on row with customer id 1005 then the AJAX call right now is:

testurl&cid=1000&checkbox=1
testurl&cid=1005&checkbox=1

$document.on('change', '.toggle-checkbox', function() {
  var $this = $(this);
  var customerid = $row.data('customerid');
  var checkState = '';

  if ($(this).is(':checked')) {
    checkState = 1;
  } else {
    checkState = 0;
  }
  
  $.ajax({
    url: base_url + "testurl",
    type: "GET",
    data: {
      cid: customerid,
      checkbox: checkState
    },
    success: function(result) {
      console.log('succesful change');
    },
    error: function(xhr, status, error) {
      console.log('unsuccesful change');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr class="test-row" data-customerid="1000">
  <td data-content="Customer ID" class="" style="max-width:700px">1000</td>
  <td class="toggle-checkbox" data-content="">
    <div class="custom-control custom-switch no-click">
      <input type="checkbox" checked="checked" class="custom-control-input toggle-checkbox" id="">
      <label class="custom-control-label" for="">&nbsp;</label>
    </div>
  </td>
</tr>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 2
    What's wrong with the code you posted? You have an `$.ajax()` call already? – HoldOffHunger Dec 02 '21 at 16:02
  • It's firing twice because you have both a `td` and an `input` with the class of `toggle-checkbox`, so clicking the `input` [bubbles](https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) to the `td`. Where does the `$row` variable come from? Also checkboxes already have a `checked` property, so you can simplify `checkState` to `this.checked + 0` – PoorlyWrittenCode Dec 03 '21 at 00:04

1 Answers1

0

why don't try this

  url: base_url + "testurl?cid="+ customerid+"&checkbox="+checkState,

and remove "data:..." from ajax

if it still is not working then

<input type="checkbox" id="row1000" checked="checked" class="custom-control-input toggle-checkbox" >

javascript

 var customerid = this.id.substring(3);
Serge
  • 40,935
  • 4
  • 18
  • 45