Reputation: 2035
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
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
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
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