Reputation: 1198
I have a jQuery ajax code that works perfectly. But I need it to change the class of the button that fires the jQuery ajax event when clicked when successful. But my code on sucess:
doesn't work. Please see code below.
jQuery Code
$(document).ready(function() {
$('.btn.btn-outline.btn-sm').click(function() {
var pollQId = $(this).val();
$.ajax({
type: "POST",
url: "Default.aspx/LikePoll",
data: JSON.stringify({ 'pollQId': pollQId }),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function() {
$(this).addClass("btn btn-primary btn-sm");
},
error: function(response) {
alert(response.d);
}
});
});
})
Please help me. Many Thanks.
Upvotes: 0
Views: 33
Reputation: 9813
The this
in the success callback is not the this
you expect, to make this param consistent to the clicked button, pass context: this
as additional param to your .ajax
function.
You can find more info from jQuery.ajax:
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).
$(document).ready(function() {
$('.btn.btn-outline.btn-sm').click(function() {
var pollQId = $(this).val();
$.ajax({
type: "POST",
url: "Default.aspx/LikePoll",
data: JSON.stringify({ 'pollQId': pollQId }),
contentType: "application/json; charset=utf-8",
datatype: "json",
// Add this param, so the `this` in the success callback
// will be the clicked button.
context: this,
success: function() {
$(this).addClass("btn btn-primary btn-sm");
},
error: function(response) {
alert(response.d);
}
});
});
})
Upvotes: 1