简体   繁体   中英

How to prevent double submission of the button

I have two buttons, one button for increasing a count and other button to submit the count and move to next page. But the error I face is that when I press the button "Proceed", it needs to be pressed twice to move to the next page and also the count is doubled and submitted. The following is the code:

Code:

  <button class="btn_success" id="btn_add" value="add areas">Confirm</button>

  <button class="brown-button" id="Proceed" onclick="location.href='gallery.php'; return false;">Proceed &nbsp;😀</a></button>

    

    var imagecount=0;

    $('.btn_success').click(function(){
      imagecount+=1;
      
      });


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

        $.ajax({
                type:'POST',
                url: 'server.php',
                data:{
                    'imagecount':imagecount,
                      },
          success: function(data){
                alert(imagecount);
                }
                })
          });

For the above code, the btn_success is used to increment the count and when I press the Proceed button, the count value is submitted and it moves to next page. But, when Proceed button is pressed , the alert pops up twice and the count value submitted is doubled ie, if the count is 3 when I press Proceed button, it is saved as 6. I want to recitfy this error and save it as value 3.

Can someone help me solve this problem

In simple terms, in your event handler (which is missing, for id="finish" there's no element), you can do something like this:

 $(function () { $("#finish").click(function () { // Cache this to use inside another function. $this = $(this); $this.prop("disabled", true); console.log("Sending AJAX call... You can't re-submit the Finish button again... Please wait..."); setTimeout(function () { console.log("Got output from server..."); $this.prop("disabled", false); }, 1000); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="finish">Finish</button>

For a better UX, you can do something like this:

 $(function () { $("#finish").click(function () { // Cache this to use inside another function. $this = $(this); $this.prop("disabled", true); $("#notification").text("Sending AJAX call... You can't re-submit the Finish button again... Please wait..."); setTimeout(function () { $("#notification").text("Got output from server..."); $this.prop("disabled", false); }, 1000); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="finish">Finish</button> <span id="notification"></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM