How can we confirm the deletion of an array element result of an ajax call?
I have an array :
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({
data: data
});
}
});
In my recursive.php
I have this code:
$arr = array(
'text' => '<img src="img/pdf.png"><a href="delete.php?doc='.$sub_data["code"].' "target="_blank">'.$sub_data["n_doc"].'</a>
'
);
In this <a href
, I need to confirm before deleting. in delete.php i have:
$sql = mysqli_query($conn, ' DELETE FROM saisie WHERE code = "'.$doc.'" ') or die (mysqli_error());
Make another ajax call in the success function:
$(document).ready(function(){
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$(document).on('click', '.btn_supp', function(){
if(confirm("do you want to delete this file?")){
$.ajax({
url: "delete.php",
method:"POST",
dataType: "json",
success: function(data)
{
alert("deleted");
});
}
});
}
});
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});`
The easiest method of accomplishing displaying a confirmation when AJAX adds to the DOM, would be to bind a delegated event listener in your view's DOMReady function.
Since jQuery binds event handlers during the DOMReady
state, it will not bind additional elements in the ajax.success
function, unless the response includes javascript and the dataType
is 'script' or you parse the data
variable from the success function and an event is manually added.
This assumes an element with an id="treeview"
, already exists.
<script type="text/javascript">
jQuery(function($) {
$(document).on('click', 'a[href^="delete.php"]', function(e) {
return window.confirm('Are you sure you want to delete this file?');
});
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data) {
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});
});
</script>
<div id="treeview"></div>
This works by telling jQuery to monitor all of the clicks inside of the #treeview
element, for a triggering element of <a href="delete.php">
. Specifically href^="delete.php"
means an <a>
element, with an href
that begins with delete.php
. If one is found, the callback function is executed and the confirmation dialog is displayed.
If you add a class
attribute to your recursive.php
anchor element, you can replace a[href^="delete.php"]
with a.classname
.
$arr = array(
'text' => '<img src="img/pdf.png"><a class="delete" href="delete.php?doc='.$sub_data["code"].'" target="_blank">'.$sub_data["n_doc"].'</a>'
);
Then in your javascript
$(document).on('click', 'a.delete', function(e) {
if (!window.confirm('Are you sure you want to delete this file?')) {
e.preventDefault();
}
});