Reputation: 931
On its own, this php works for deleting multiple values when the (controlpanel.php) input html name is "checkbox[]", however I'm not sure how to deal with these $_POST values using jquery? I tried putting "checkbox[]" on the id but that didn't work. When I tried vardump($_POST) I just got the same value each time no matter how many checkboxes were ticked.
test_process.js
$('#delete_submit').on('click', function(event) {
alert("Test");
event.preventDefault();
var delete_value = $('#checkbox').val();
$.post('ajax/name.php', {delete_template: delete_value}, function(data) {
$('div#delete_data').text(data);
});
});
ajax/name.php
<?php
include('C:\xampp\htdocs\email1\class\db.php');
require_once('C:\xampp\htdocs\email1\config\db.php');
require_once('C:\xampp\htdocs\email1\class\Login.php');
$login = new Login();
$user = $_SESSION['user_name'];
$db = new Database();
$db->connect();
//delete
if (isset($_POST['delete_template'])) {
foreach($_POST as $value){
$db->delete('templates','template_name="'.$value.'"');
echo $value. " has been successfully deleted.";
}
}
Controlpanel.php
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<form action="ajax/name.php" name="delete_template_form" id="delete_template_form" method="post">
<?php print "<table border=\"1\">
<th>Template Name</th>
<th>Template Description</th>
<th> </th>";
foreach($res as $row){
echo "<tr>";
echo "<td>". $row['template_name']. "</td>";
echo "<td>". $row['template_description']. "</td>";
echo "<td><input type=\"checkbox\" value=".$row['template_name']." name=\"checkbox\" id=\"checkbox\"></td>";
echo "<tr/>";
}
print "</table>"; ?>
<br/><button type="button" name="delete_submit" id="delete_submit">Delete</button>
</form>
<div id="delete_data"></div>
<script type="text/javascript" src="test_process.js"></script>
</body>
</html>
Upvotes: 0
Views: 703
Reputation: 12433
id
are supposed to be unique, and since you are using the same id
for every checkbox -> id=\"checkbox\"
, var delete_value = $('#checkbox').val();
will only select the 1st instance of id=\"checkbox\"
.
1- change your checkboxes to an array (name=\"checkbox[]\"
) and your id
s to something unique (id=\"checkbox".$row['id']."
) -
echo "<td><input type=\"checkbox\" value=".$row['template_name']." name=\"checkbox[]\" id=\"checkbox".$row['id']."\"></td>";
2- change your javascript to serializing your form inputs and send that as your data $('#delete_template_form').serialize()
-
$.post('ajax/name.php', $('#delete_template_form').serialize() , function(data) {
$('div#delete_data').text(data);
});
3- then in your php, loop through your checkboxes
if (isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $value){
$db->delete('templates','template_name="'.$value.'"');
echo $value. " has been successfully deleted.";
}
Upvotes: 2