Sunday, 11 September 2016

AJAX - change class of $(this) in case of success error solution

this is not automatically a reference to the right object in the ajax callback. You can change that by closing over a variable that does have the right value:
$("#someDiv .myClass").each(function() {
    var $this = $(this);
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {
            $this.removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​
or by using the context option of $.ajax():
$("#someDiv .myClass").each(function() {
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        context: this,
        success: function(data) {
            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​
JQUERY AJAX - change class of $(this) in case of success

No comments:

Post a Comment