4

I am trying to insert data into the database using ajax call

my problem is when I click the button twice the data is storing twice

and it is making me sick. How can I avoid it?

<from><button id ="GdStartTest"> </button></form>
$("#GdStartTest").click(function(){
$.ajax({
    url: "gdcontroller.php",
    method: "POST",

And this controller:

$studentQuery = $conn->query("INSERT INTO r_job_scores 
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Mr world wide
  • 4,696
  • 7
  • 43
  • 97

3 Answers3

8

Disable the button immediately after clicking it and enable it within the ajax complete callback.

$("#GdStartTest").click(function(){

    // cache the button reference
    var $this = $(this);

    // disable the button
    $this.prop('disabled', true);

    $.ajax({
        url: "gdcontroller.php",
        method: "POST",
        .........
        complete : function(){
          // enable the button
          $this.prop('disabled', false);
       },
 ......

Or use one() method to execute the event handler only once.

$("#GdStartTest").one('click', function(){
    $.ajax({
        url: "gdcontroller.php",
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 2
    I would rather put it in the "complete" callback so it gets executed no matter how the ajax call ended. – Mike Jan 09 '17 at 07:31
  • @Mike : yes, that's a perfect way... I will update the answer... Thanks m:) – Pranav C Balan Jan 09 '17 at 07:33
  • I don't get why - but the top method "disable" didn't work for me - I could always get 2-3 clicks to work. The "one()" method worked 100% for me. – Scott Aug 22 '22 at 19:22
2

There are so many options to achieve this like, disable the button, put the event listener to off like:

$("#GdStartTest").click(function(){
    $(this).prop('disabled', true);
});

$("#GdStartTest").click(function(){
    $("#GdStartTest").off();
});
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
2
  1. Disable the button.
  2. Use a Loader on ajax using beforeSend as another parameter.

       $.ajax({
               beforeSend: function(){
                   $(".loader").show();
               }
       });
    
Sabarish
  • 126
  • 1
  • 10