Javascript
Da du bruger jquery, er der en bedre måde :)
<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
En enkelt forespørgsel er nok :)
<?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.")" );
}
}
?>
Og husk, det er ikke godt at gøre alt dette på klientsiden.
Du kan gøre POST
anmode om en enkelt fil, da din hver input
knappen har et unikt navn.
Så i din PHP
kode, kan du finde hvilken knap der blev klikket på sådan her.
<?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.")" );
}
?>
se hvor simpelt :) Er det ikke?