roundtheworld roundtheworld - 3 months ago 10
Ajax Question

Why won't removeClass() and addClass() work?

I have an AJAX call that will execute successfully, but when it reaches the

done()
section, it will print out my message "SUCCESS" but not change the classes of the button.

$(".btn").click(function () {
$.ajax({
method: "POST",
url: $(this).data("action"),
data: {
aId: $(this).data("a-id"),
bId: $(this).data("b-id"),
cId: $(this).data("c-id")
}
})
.done(function () {
console.log("SUCCESS");
$(this).removeClass("btn-default");
$(this).addClass("btn-success");
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert("FAILURE");
$(this).removeClass("btn-default").addClass("btn-danger");
});
});


My guess is that it has to do with that fact that I'm not giving the function a ID of the button to act on, but to act on anything that is clicked that has the class "btn." The page this originates from has a long list of buttons which is why they don't have IDs since the page would give them all the same ID. I suppose I could append a number to the ID, but I would prefer not to do it that way. It also doesn't explain why
$(this)
works in the rest of my AJAX function when retrieving values.

Answer

$(this) isn't the right this. Try caching the element.

$(".btn").click(function () {
    var $btn = $(this);

    $.ajax({
        method: "POST",
        url: $(this).data("action"),
        data: {
            aId: $(this).data("a-id"),
            bId: $(this).data("b-id"),
            cId: $(this).data("c-id")
        }
    })
    .done(function () {
        console.log("SUCCESS");
        $btn.removeClass("btn-default");
        $btn.addClass("btn-success");
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        alert("FAILURE");
        $btn.removeClass("btn-default").addClass("btn-danger");
    });
});
Comments