2

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
  • 62,337
  • 13
  • 111
  • 105
Mr world wide
  • 4,406
  • 7
  • 38
  • 89

3 Answers3

6

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
  • 110,383
  • 23
  • 155
  • 178
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
  • 24,624
  • 3
  • 35
  • 55
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