Jeroen Bellemans
Jeroen Bellemans

Reputation: 2035

Span addClass not working ajax

I have a span like this <span class="join-event to-join">join event</span>. I use this function to do something with the click via AJAX.

But in the success function I can't seem to add a class to that clicked span.

function accept() {

    $(".to-join").click(function() {

        var id = $(this).attr("data-event");

        $.ajax({

            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {

                alert("good job");
                $(this).addClass("joined");

            },

            error: function () {

                alert("fail");

            }

        });

    });

}

Upvotes: 1

Views: 221

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

Use context option of ajax method:

context: this,

context Type: PlainObject This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

Upvotes: 5

Thomas Montagnoni
Thomas Montagnoni

Reputation: 468

$(".to-join").click(function() {
        var span = $(this);
        var id = $(this).attr("data-event");

        $.ajax({

            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {

                alert("good job");
                span.addClass("joined");

            },

            error: function () {

                alert("fail");

            }

        });

    });

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

You need to define $(this) as variable outside the ajax call, this inside ajax will refers to jqXHR object

function accept() {    
    $(".to-join").click(function() {    
        var id = $(this).attr("data-event"),
              $this=$(this);    
        $.ajax({    
            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {    
                alert("good job");
                $this.addClass("joined");    
            },    
            error: function () {    
                alert("fail");    
            }    
        });    
    });    
}

Upvotes: 4

Related Questions