I am new to coding and I am trying to create a button to use bootstrap 5 to delete a client form a sql database.
I am using datatables and the button is formed like this:
<li><button class="dropdown-item testing" name= ' + item.client_id + ' aria-label="delplan" type="button"><i class="far fa-trash-alt styleicon"></i>Verwijder</button></li>
I am using the folowing script to retrieve to open the modal with bootbox and get the ID from the name tag in my button.
$(document).ready(function(){
var table = $('#clientTable').DataTable();
$("#clientTable").on("click", ".testing", function () {
var id = $(this).attr('name');
console.log(id); // this is correctly showing the id in the console !
bootbox.confirm({
title: "Verwijder client?",
message: "Weet je zeker dat je deze client wilt verwijderen van de database?",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
var id = $(this).attr('name');// the post is empty and the console says undefined, so tried to get it here to, but still undefined.
var p = loadPrompt();
if(result === false){
console.log('clicked no: ' + id); // console log clicked no undefined..
p.inform('Client is niet verwijderd!');
}
else{
console.log('clicked yes: ' + id); // console log clicked yes undefined..
$.ajax({
type: "POST",
url: "client_delete_client.php",
data: {id: id}, // post request is happening in network tab but no data is send??
success: function(data) {
$('#clientTable').DataTable().ajax.reload();
p.success('Client is succesvol verwijderd! ');
},
error: function(xhr, status, error) {
alert("ERROR : Something went wrong! Try again our contact the database administrator" + error);
p.error('Fout in het verwijderen van client !');
}
});
}
}
});
});
});
</script>
I do not understand why my script is not posting the var id to url client_delete_client.php after the client clicked yes? I hope than there is someone here that can help me. Because the id is loged in the console at first but after that is is undefined?
The problem is one of JavaScript scope. Inside your callback function this refers to something else, probably the callback function itself but a console.log(this) would confirm it.
The solution is to create a reference to your button right after the click event:
$("#clientTable").on("click", ".testing", function () {
const btn = this;
}
then refer to btn elsewhere in your code
const id = $(btn).attr('name');
I recommend that you do some reading about scope in JavaScript, particularly with how it affects the this variable (but also other variables) because it's something that trips up a lot of developers.