Am sending requesty by ajax to insert data in database. After success submiting my button message was not changed. On press i fire message Please wait...
when success is fired set new html value Done
. Records in db is success created but button text to Done
was not changed.
My script:
var Friend = {
// Add new friend
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
$(this).html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Not wortk
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});
});
},
// Initialise
init: function() {
Friend.add();
}
};
Html:
<button type="button" id="item-<?=$person->account_id;?>" class="btn btn-xs btn-add-friend has-spinner" data-friend="<?= $person->account_id;?>"><i class="fa fa-plus-circle"></i> Add Friend</button>
When i click on button text was changet to Please wait..
but after success not changed to Done
and alert is successful executed.
looks like it is not part of DOM after click! ALso i try with on()
the some result i get.
this
inside the ajax function callbacks is .... the ajax call, not the clicked element.
You have to replace it with it
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
var self = $(this);
self.html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: self.data('friend')
},
success: function(xhr, status) {
self.html("Done");
},
To use this
, you need additional attribute. Add the following with url
context:this
So, the updated code will be
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
context:this,
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Will work
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});
Inside the callback, this refers to the jqXHR
object of the Ajax call, not the element. so try to assign it to a variable before ajax request, then use this variale inside success function:
//Before ajax request
var _this = $(this);
//Inside success function
_this.html("Done");
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.