Is there a way not to send it in duplicate when sending it to the server through Ajax?

Asked 1 years ago, Updated 1 years ago, 79 views

Is there a way to prevent duplicate sending of user-written information to the server via asynchronous communication after clicking the button?

fast-frontend ajax double submit

2022-09-22 08:44

2 Answers

Hello, IoIetc. :-)

I think the key point of your question is not to receive the same (redundant) request during the Ajax transfer request.

The easiest way to solve this problem is to create and use a state variable. It's about making or blocking Ajax requests depending on the status of the transmission.

The transmission status will initially be false, and when you click the button, condition processing is used to set the request only if false. When in transit, set the value of the status variable to true to prevent the user from requesting a transfer even if they click again during the transfer.

When the transfer is complete, always change the value of the transfer status variable to false regardless of success or failure to make it clickable again after the transfer is complete.

The code can be written as follows: Please refer to it. :)

// Send Ajax button
var ajaxButton = document.querySelector('.ajax-button');

// Set transmission status: false
var isSubmitted = false;

var ajaxSend = function() {

  // If the transmission status is false, condition handling
  if ( !isSubmitted ) {
    // Change transmission status: true
    isSubmitted = true;
    // Add disabled property of button element
    ajaxButton.setAttribute('disabled', 'disabled');

    // Ajax Server Communication Code
    $.ajax({...}).always(function(){
      // Transfer status change regardless of transfer success or failure: false
      isSubmitted = false;
      // Remove the disabled property of a button element
      ajaxButton.removeAttribute('disabled');
    }); 

  }
};

// Ajax Transfer Button Event Handling
ajaxButton.addEventListener('click', ajaxSend);


2022-09-22 08:44

Your question is double submit problem.


2022-09-22 08:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.