Search code examples
javascriptajaxdisabled-controlprop

How to temporarily disable a button within an Ajax call?


In my Javascript code, I wrote an Ajax call where a couple of for loop cycles call two JSON files; some functions are called when some events occur and a Search button is clicked: tables containing data from the APIs requests are displayed.

I want to temporarily disable the Search button when these data are looked for within the Ajax calls, and then enable it again once the operation was carried out, in a way similar to what happens in the setTimeout() Method, but without having to set a number of milliseconds (I cannot specify it previously for the number of milliseconds depends on the slowness of the internet connection and other factors...).

How to set the .prop("disabled", false); temporarily within a callback function? In other terms, how to temporarily disable a button within an Ajax call?


Solution

  • You can make use of beforeSend and complete for this,

    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        beforeSend: function() {
            // disable your button here
            .prop("disabled", true);
        },
        success: function(data) {
            //success
        },
        error: function(xhr) { // if error occured
        },
        complete: function() {
            // enable your button here
            .prop("disabled", false);
        }
    });