skip to Main Content

I have the following Ajax Code for submitting data to Mysql DB.

<script>
var amountdue;
var amount;
$('#btn-submit').on('click',function(e){
  e.preventDefault();
  if ($("#customer").validationEngine('validate')) {
    swal({
      title: "Submit Confirmation",
      text: "Are you sure to submit the data?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#126495",
      confirmButtonText: "Submit",
      closeOnConfirm: false
    }, 
    function(isConfirm){
      if (isConfirm) {
        amountdue =  "<?php echo $amount_due;?>";
        amount = "<?php echo $amount;?>";
        $.ajax({
          type: "POST",
          url: "submit.php",
          cache: false,
          dataType : "text",
          data: {amountdue : amountdue, amount : amount},
          success: function(data) {
            window.location.href = 'customers';
          },
          error: function(result) {
            swal({
              title: "Error",
              type: "warning",
              text: "Sorry, the data could not be updated due to some reasons.",
              confirmButtonColor: "#126495"
            });
          }
        });
      } //confirm
    });
  }
});
</script>

The issue is that sometimes (Not always) data is getting inserted 2 and more times in mysql DB..How can i prevent this behavior on Ajax Submit ??

will $('#btn-submit').unbind();

work on success ?? Requesting help…

2

Answers


  1. Try this:

    As the first line of your click event handler, do

    e.disabled = true;
    

    Then, in both your success and error handlers for AJAX, do this

    e.disabled = false;
    

    The point of this is to suppress unintentional double clicks on your button until the AJAX operation finishes.

    Login or Signup to reply.
  2. $('#btn-submit').off().on('click',function(e){
     ……..Your code...
    

    Try like this.

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