admin管理员组

文章数量:1302542

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 

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 
Share Improve this question edited Jan 9, 2017 at 7:24 Suren Srapyan 68.7k14 gold badges125 silver badges117 bronze badges asked Jan 9, 2017 at 7:23 Mr world wideMr world wide 4,8449 gold badges45 silver badges105 bronze badges 3
  • $("#GdStartTest").click(function(e){e.stopPropagation();... rest of the code – Death-is-the-real-truth Commented Jan 9, 2017 at 7:26
  • Possible duplicate of bind event only once – Death-is-the-real-truth Commented Jan 9, 2017 at 7:28
  • Lol re: "making me sick" – Mulan Commented Jan 9, 2017 at 7:31
Add a ment  | 

3 Answers 3

Reset to default 8

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

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

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

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

    $.ajax({
        url: "gdcontroller.php",
        method: "POST",
        .........
        plete : 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",

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();
});
  1. Disable the button.
  2. Use a Loader on ajax using beforeSend as another parameter.

       $.ajax({
               beforeSend: function(){
                   $(".loader").show();
               }
       });
    

本文标签: javascriptHow to AvoidAjax button click twiceStack Overflow