This is a short tutorial on how to disable a button until an Ajax request has been completed. In this guide, I will be using the JavaScript library JQuery to disable the button and send the Ajax request.
Lets take a look at the following code:
<!DOCTYPE html> <html> <head> <title>Disable Button Until Ajax Request Complete</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> </head> <body> <p>Click the button below to disable it!</p> <button id="ajax_button">Send Ajax Request</button> <script> //Add a click event handler to our button. $('#ajax_button').on('click', function(){ //Disable our button $('#ajax_button').attr("disabled", true); //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; $.ajax({ url: url, success: function(data){ //The Ajax request was a success. //Do something in here. }, complete: function(){ //Ajax request is finished, so we can enable //the button again. $('#ajax_button').attr("disabled", false); } }); }); </script> </body> </html>
In the example above:
- We included the JQuery libary from the JQuery CDN.
- We created a simple HTML button with the ID “ajax_button”.
- After that, 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.