Javascript
Karena Anda menggunakan jquery, ada cara yang lebih baik :)
<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
Satu permintaan saja sudah cukup :)
<?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.")" );
}
}
?>
Dan ingat, tidak baik melakukan ini semua di sisi klien.
Anda dapat melakukan POST
permintaan ke satu file, karena setiap input
tombol memiliki nama yang unik.
Jadi di PHP
your Anda kode, Anda dapat menemukan tombol mana yang diklik seperti ini.
<?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.")" );
}
?>
lihat betapa sederhananya :) bukan?