Javascript
Eftersom du använder jquery finns det ett bättre sätt :)
<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 enda fråga räcker :)
<?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.")" );
}
}
?>
Och kom ihåg att det inte är bra att göra allt på klientsidan.
Du kan göra POST
begära till en enda fil, eftersom varje input
knappen har ett unikt namn.
Så i din PHP
kod, kan du hitta vilken knapp som klickades på så här.
<?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.")" );
}
?>
titta så enkelt :) Är det inte?