Reputation:
I tried implementing SweetAlert2 to my code, I tried to call a function from the trigger button unsuccessfully.
any idea how to fix this code in order for it to work?
$(".delete").click(function () {
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
delete_post($(this).attr("id"));
swal(
'Deleted!',
'Your file has been deleted.',
'success'
)
})
})
});
the called function:
function delete_post(id) {
var info = {"delete_post_id":id};
$.post('index.php',
info
).done(function( response ) {
if(response["error"]) {
$('#error').html(response["error"]);
}else{
window.location = "index.php";
}
});
}
Upvotes: 1
Views: 594
Reputation: 3501
As @Halil said, it's because of this
in your callback from the alert, this
does not refer to your button in the callback, it refers to the callback function itself.
Assign the id to a variable before you display the alert so that you can use it in the callback like so:
$(".delete").click(function() {
console.log('Delete button has been clicked...');
// get the id
var id = $(this).attr("id"));
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function() {
console.log('Confirm button clicked...');
// use the id we declared earlier
delete_post(id);
swal(
'Deleted!',
'Your file has been deleted.',
'success'
);
});
});
function delete_post(id) {
console.log('Deleting post...', id);
var info = {
"delete_post_id": id
};
$.post('index.php', info)
.done(function(response) {
console.log('Completed request...', response);
if (response["error"]) {
$('#error').html(response["error"]);
} else {
window.location = "index.php";
}
});
}
I also added some console.log debugging so you can see what's going on when you run it in your browser.
Upvotes: 1
Reputation: 19
type console.info(this);
before then this row :
delete_post($(this).attr("id"));
i think this
is your function in then.
Upvotes: 1