PHP While Delete button with JS confirm box?
I have a while script running on my page, i want to add a delete button for every result, but before they will be able to delete i want a javascript popup to popup asking them if they sure they want to delete it. Just asking what is the best way to do it? (I will run the delete function using Ajax because i don't want to navigate away from the开发者_运维知识库 page after the deletion).
Here is the code I'm using, so far everything works - the results are showing and the delete buttons are popping up the confirm box. And now I'm stuck.
Pop-up:
<script type="text/javascript">
window.show_confirm = function() {
var r = confirm("Are you sure you want to delete?");
if (r == true) {
alert(" I NEED TO DO SOMETHING HERE? ");
} else {
alert("The item won't be deleted.");
}
}
</script>
PHP While:
<?php
while ($row_apps = mysql_fetch_array($result_apps))
{
if ( ($row_apps['type'] == 'ar') && ($row_apps['client'] == NULL) ) {
echo '<center>
<div id="tab_listing">
<table width="248" border="0" cellspacing="10px" cellpadding="0px">
<tr>
<td width="100%" colspan="3"><div class="tab_listing_header">'.$row_apps['app_name'].'</div></td>
</tr>
<tr>
<td class="tab_listing_values"><b>App ID: </b>'.$row_apps['app_id'].'</td>
<td class="tab_listing_values"><b>Users: </b>'.$row_apps['users'].'</td>
</tr>
</table>
<div id="edit">Edit</div>
<a href="#" onclick="return show_confirm()"><div id="delete"></div></a>
</div>
</center><br>';
}
}
?>
If someone could suggest a way to do that ill be grateful :)
At first, you shouldn't use the same id within a loop! If you have multiple elements, use class! But it could be useful also to have an id, so bind it to a unique element of your output:
<div id="_<?php echo $row_apps['app_id']; ?>" class="tab_listing">
In order to reference the entry you want to delete, you have to pass something like an ID to the delete-function, for instance
<a href="#" onclick="return show_confirm(<?php echo $row_apps['app_id']; ?>)"><div id="delete"></div></a>
So the script must look like this:
<script>
window.show_confirm = function(id) { //notice the passed in parameter
var r = confirm("Are you sure you want to delete?");
if (r == true) {
alert(" I NEED TO DO SOMETHING HERE? ");
//now do an ajax-request with the id you want to delete
//after the request, do something with the div ('_'+id),
//e.g. hide or add a text.
//with jQuery it's 1 line of code:
// $.post('delete.php', {'id':id}, function(data){$('#_'+id).html('Deleted!')});
} else {
alert("The item won't be deleted.");
}
}
</script>
For AJAX stuff, I recommend using jQuery - it will save you a lot of work!
And the delete.php could look something like this:
<?php
if(isset($_POST['id'])) {
$id = $_POST['id'];
//do something with the id...
}
?>
精彩评论