Lets take a look at the following code:
<title>Disable Button Until Ajax Request Complete</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<p>Click the button below to disable it!</p>
<button id="ajax_button">Send Ajax Request</button>
//Add a click event handler to our button.
//Disable our button
//The URL that we are sending an Ajax request to.
//For this example, I'm sending a Ajax request to the current page.
var url = window.location.href;
//The Ajax request was a success.
//Do something in here.
//Ajax request is finished, so we can enable
//the button again.
In the example above:
- We included the JQuery libary from the JQuery CDN.
- We created a simple HTML button with the ID “ajax_button”.
- We added an “onclick” event handler to our button.
- As soon as the “onclick” event is fired, we disable the button in question.
- Once the button has been disabled, we carry out a simple Ajax request.
- Inside the “complete” callback function of our Ajax request, we re-enable the button again. This “complete” callback function is called once the request has finished – regardless of whether it was successful or not.
Note: In some cases, you might choose to re-enable the button inside the “success” callback function. However, if an error occurs and the Ajax request fails, then the button will not be re-enabled. Before you do this, make sure that you are OK with the button remaining in a disabled state if an error occurs.