Disable Button Until Ajax Request Is Complete

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:

In the example above:

  1. We included the JQuery libary from the JQuery CDN.
  2. We created a simple HTML button with the ID “ajax_button”.
  3. We added an “onclick” event handler to our button.
  4. As soon as the “onclick” event is fired, we disable the button in question.
  5. Once the button has been disabled, we carry out a simple Ajax request.
  6. 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.

Comments

comments