Javascript
Aangezien je jQuery gebruikt, is er een betere manier :)
<script type="text/javascript">
var is_activate = true; // we will track which input button was clicked :)
jQuery(function($) {
$("#form input#check_all").change(function() {
var inputs = $("#form input[type='checkbox']");
if ( $(this).is(":checked") ) {
inputs.prop( "checked", true );
// inputs.attr( "checked", true ); // if its not working
}
else {
inputs.removeAttr( "checked" );
}
});
// Track clicked button
$("#form input[type=submit]").on("click",function(e) {
is_activate = ( $(this).hasClass("activate_btn") ) ? true : false;
});
$("#form").submit(function(e) {
e.preventDefault();
var string = ( is_activate ) ? 'activate' : 'delete';
var data = $(this).serialize();
var checked = $(this).find("input[name='data[]']:checked").length;
if ( checked == 0 ) {
alert( "Please select a comment(s) to "+string+"." );
return false;
}
var text = "Are you sure you want to "+string+" these comment"+( ( checked == 1 ) ? "?" : "s?" );
if ( confirm( text ) ) {
$.ajax({
url: 'resources/ajax/'+( ( is_activate ) ? 'ajax_activate_comment.php' : 'ajax_delete_comment.php' ),
type: 'post',
data: data,
success: function( data ) {
}
});
}
});
});
</script>
HTML
<form method="post" id="form">
<label>Check All</label>
<input type="checkbox" id="check_all" value="">
<label>Here im displaying record from database and</label>
<input name="data[]" type="checkbox" id="data1" value="1">
<input name="data[]" type="checkbox" id="data2" value="2">
<!-- Activate Button -->
<input class="activate_btn" type="submit" name="activate" value="Activate" id="submit">
<!-- Delete Button -->
<input class="delete_btn" type="submit" name="delete" value="Delete" id="submit">
</form>
PHP
Een enkele vraag is genoeg :)
<?php
if ( isset( $_POST['data'] ) ) {
$id_array = $_POST['data'];
if ( !empty( $id_array ) ) {
$id_array = implode( ",", $_POST['data'] ); // dont forget to sanitize
$sql = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
}
}
?>
En onthoud, het is niet goed om dit allemaal aan de clientzijde te doen.
Je kunt POST
doen verzoek aan een enkel bestand, aangezien uw elke input
knop heeft een unieke naam.
Dus in je PHP
code, kunt u zien op welke knop op deze manier is geklikt.
<?php
if ( isset( $_POST["activate"] ) ) {
$sql = $db->query( "UPDATE comments SET status = '1' WHERE `id` IN (".$id_array.")" );
}
else {
$sql = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
}
?>
kijk hoe simpel :) Is het niet?