1

If I click the Submit button once then the AJAX call is executed only once. This is perfect.

The problem is if I don't refresh the page and click the Submit button for the second time, then the AJAX call is executed twice. If I click the button for a third time without refreshing the page, the AJAX call is executed thrice.

What is wrong with my code? I want the AJAX call to be executed only once when I click the Submit button.

<form id="myForm">
  <div class="modal-dialog" role="document">
    <input type="hidden" name="buttonId" id="buttonId">
    <div class="modal-content">
      <div class="modal-body">
        <div class="input-group">
          <span id="commspan" class="input-group-addon">Comment</span>
          <input type="text" name="queuqOther" id="queuqOther" class="form-control">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" id="btnPause" class="btn btn-primary">Submit</button>
      </div>
    </div>
  </div>
</form>
$('#btnPause').on('click', function() {
  var form = $("#myForm");
  form.validate();
  if (form.valid()) {
    $.ajax({
      async: true,
      crossDomain: true,
      url: "http://localhost/postdata",
      xhrFields: {
        withCredentials: true
      },
      success: function(data) {
        console.log(data);
      }
    });
  }
});
2
  • $('#btnPause').off().on('click'... You keep attaching a new handler every time. Commented Dec 19, 2018 at 11:38
  • Nothing about your the code you've shown is attaching multiple event handlers, so I'm unsure why people are suggesting off(). Is there any other logic called when the AJAX returns as this code will not cause the behaviour you describe Commented Dec 19, 2018 at 11:48

4 Answers 4

2

The easiest tweak would be to remove the listener once you check that the form is valid:

const $btnPause = $('#btnPause');
const handler = function() {
  var form = $( "#myForm" );
  form.validate();
  if(form.valid()){
    // remove handler:
    $btnPause.off('click', handler);
    $.ajax({
      async : true,
      crossDomain: true,
      url: "http://localhost/postdata",
      xhrFields: {
        withCredentials: true
      },                            
      success: function (data) {
        console.log(data);
      }
    });
  }
};

$btnPause.on('click', handler);
Sign up to request clarification or add additional context in comments.

10 Comments

Seems fine to me jsfiddle.net/w159bj24 What exactly is the error you're running into?
@CertainPerformance the OP isn't binding multiple events here, so I don't see why off() would make any difference.
@RoryMcCrossan I thought the problem was that multiple clicks of "submit" result in multiple ajax calls, for which I thought the obvious solution was to just remove the handler the first time an ajax call is getting sent out. Am I missing something?
I removed $btnPause.off('click', handler); and changed $btnPause.on('click', handler); to $btnPause.unbind().bind('click', handler); and it worked
Thank you very much. Please update your answer with what I suggested above so that it will help others :)
|
2

Try removing click event handler with off() as Following

$('#btnPause').off('click').on('click',function() {
  var form = $( "#myForm" );
  form.validate();
  if(form.valid()){
    $.ajax({
              async : true,
              crossDomain: true,
              url: "http://localhost/postdata",

              xhrFields: {
                 withCredentials: true
                },                            
              success: function (data) {
                console.log(data);
                  }
          });
    }
});

You can also use one() to execute the event handler at most once

$('#btnPause').one('click',function() {/* your code here */});

Comments

1

Always unbind the event handlers once you complete binding. For eg. use .off() for .on() attached events.

$('#btnPause').off('click').on('click', function() {
//your Code Here
});

Comments

0
const $btnPause = $('#btnPause');
const handler = function() {
  var form = $( "#myForm" );
  form.validate();
  if(form.valid()){
    // remove handler:
    $btnPause.off('click', handler);
    $.ajax({
      async : true,
      crossDomain: true,
      url: "http://localhost/postdata",
      xhrFields: {
        withCredentials: true
      },                            
      success: function (data) {
        console.log(data);
      }
    });
  }
};

$btnPause.on('click', handler);

1 Comment

Hi, Welcome, It is recommended to explain your code when posting the answer please :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.