'Enable and disable button with ajax content response

I cannot get why its not working with me. I know to enable and disable button using attr and prop.

 $(document).on("click", "#btn", function(){
      $(this).html("Sending...");
      $(this).prop("disabled",true);
      // I have ajax content here. and in success of ajax. run
      $(this).prop("disabled",false);

The button disable is not enabled in ajax success. Do my code has any problem.



Solution 1:[1]

Inside ajax do not use $(this), instead you can do this:

$(document).on("click", "#btn", function(){
     var button = $(this);

Inside ajax, then you can use this:

button.prop("disabled",true);

Solution 2:[2]

try this

$(this).attr("disabled", "disabled");

Solution 3:[3]

You need to save a reference to this if you wish to refer to it in another function:

$(document).on("click", "#btn", function(){
    var button = $(this);
    button.html("Sending...");
    button.prop("disabled",true);
    // I have ajax content here. and in success of ajax. run
    button.prop("disabled",false);

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Solution 4:[4]

$(this) in AJAX does not refer to the button, instead use:

$('#btn').prop("disabled",false);

Solution 5:[5]

use async : true as below :)

$('#button').attr("disabled", true);
$.ajax({
            url: url,
            data: data,
            type: 'post',
            dataType: 'json',
            cache: false,
            async: true,
            complete: function(response){
                $('#button').attr("disabled", false);
            },
        });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 renakre
Solution 2 Mohamed Badr
Solution 3 ekuusela
Solution 4 Samurai
Solution 5 Guru