vendredi 21 juillet 2017

Uncheck checkbox if AJAX error

I have a table with a checkbox in the first column - when checked this performs an AJAX script that updates a PHP session variable with the selected values. If there is an AJAX error I would like the checkbox to remain unchecked - at the moment it will remain checked when there is an AJAX error with the script.

Here's the table and the script:

$(document).ready(function() {
  $("input.select-item").click(function() {
    var productID = $(this).val();
    // Create a reference to $(this) here:
    $this = $(this);
    $.post('productSelections.php', {
      type: 'updateSelections',
      productID: productID,
      selectionType: 'single'
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Product Selections';
        $this.closest('td').addClass("has-error");
        $("#updateSelectionsErrorMessage").html(errorAlert);
        $("#updateSelectionsError").show();
        return; // stop executing this function any further
      } else {
        $this.closest('td').addClass("success")
        $this.closest('td').removeClass("danger");
      }
    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Product Selections';
      $this.closest('td').addClass("danger");
      $("#updateSelectionsErrorMessage").html(ajaxError);
      $("#updateSelectionsError").show();
    });
  });
});
<script src="http://ift.tt/1Rv0lZ3"></script>
<table class="table table-condensed table-striped table-bordered">
  <thead>
    <th><input type="checkbox" class="select-all checkbox" name="select-all" /></th>
    <th class="text-center" scope="col">Product ID</th>
    <th class="text-center" scope="col">Description</th>
  </thead>
  <tbody>

    <tr class="" id="85799">
      <td id="AT36288"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36288" /></td>
      <td>AT36288</td>
      <td>Apples</td>
      <td></td>
    </tr>
    <tr class="" id="85800">
      <td id="AT36289"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36289" /></td>
      <td>AT36289</td>
      <td>Bananas</td>
      <td></td>
    </tr>
    <tr class="" id="85801">
      <td id="AT36290"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36290" /></td>
      <td>AT36290</td>
      <td>Oranges</td>
      <td></td>
    </tr>
    <tr class="" id="85803">
      <td id="AT36292"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36292" /></td>
      <td>AT36292</td>
      <td>Grapes</td>
      <td></td>
    </tr>
  </tbody>
</table>

I'm adding an error class to colour the red and also display an alert, but would like to prevent the check box from remaining checked if possible.




Aucun commentaire:

Enregistrer un commentaire