checkbox column on Server side processing and remember selected checkboxes and saving stage between pages

Datatable serverside example following thease
 1.Checkbox column on Server side processing
 2.Remember selected checkboxes
 3.Saving stage between pages
 4.Get all the values of the checked checkboxes
 5.Edit and Delete with serverside processing
 6.Select All and UnSelect all checkboxes

Screen 1
Screen 2



<?php
$sql = "delete from GUEST_EVENT
where
GUEST_ID=$_REQUEST[guestID]";
$dbCards=mysqli_connect("127.0.0.1","root","pinturp1","mycardco_marriage");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($dbCards,$sql);
mysqli_close($dbCards);
?>
<?php
session_start();
if($_REQUEST['IS_MAIL'] != 0 || $_REQUEST['IS_TEXT'] != 0 || $_REQUEST['IS_CALL'] != 0)
{
$sql = "select * from GUEST_EVENT where EVENT_ID in (select EVENT_ID from events where UID_INT=$_SESSION[userId])";
$dbCards=mysqli_connect("127.0.0.1","root","pinturp1","mycardco_marriage");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($dbCards,$sql );
mysqli_close($dbCards);
while($aRow = mysqli_fetch_array($result))
{
$dbCards=mysqli_connect("127.0.0.1","root","pinturp1","mycardco_marriage");
$sql = "INSERT INTO mycardco_marriage.TO_INVITE
(
GUEST_ID,
IS_MAIL,
IS_TEXT,
IS_CALL
)
VALUES
(
$aRow[GUEST_ID],
$_REQUEST[IS_MAIL],
$_REQUEST[IS_TEXT],
$_REQUEST[IS_CALL]
)";
if (!mysqli_query($dbCards,$sql))
{
die('Error: ' . mysqli_error($dbCards));
}
}
}
else
{
echo "Sorry";
}
?>
<?php
if($_REQUEST['IS_MAIL'] != 0 || $_REQUEST['IS_TEXT'] != 0 || $_REQUEST['IS_CALL'] != 0)
{
session_start();
$selectedGuests_array = explode(",", $_REQUEST['selectedGuests']);
for($i=0; $i<count($selectedGuests_array); $i++)
{
$dbCards=mysqli_connect("127.0.0.1","root","pinturp1","mycardco_marriage");
$sql = "INSERT INTO mycardco_marriage.TO_INVITE
(
GUEST_ID,
IS_MAIL,
IS_TEXT,
IS_CALL
)
VALUES
(
$selectedGuests_array[$i],
$_REQUEST[IS_MAIL],
$_REQUEST[IS_TEXT],
$_REQUEST[IS_CALL]
)";
if (!mysqli_query($dbCards,$sql))
{
die('Error: ' . mysqli_error($dbCards));
}
}
}
else
{
echo "Sorry";
}
?>
<?php
session_start();
$sql = "update mycardco_marriage.GUESTS2
set
name_vch='$_REQUEST[guestName]',
email_vch='$_REQUEST[guestEmail]',
phone_vch='$_REQUEST[guestPhone]',
address_vch='$_REQUEST[guestAddress]'
where
PK_ID=$_REQUEST[id]" ;
$dbCards=mysqli_connect("127.0.0.1","root","pinturp1","mycardco_marriage");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($dbCards,$sql);
mysqli_close($dbCards);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script language="javascript" src="js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css"/>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables_themeroller.css"/>
<script>
$(document).ready(function()
{
var oTable;
//--Start: Select And UnSelect All CheckBoxes
$('#Select_All').click(function()
{
$('input[type="checkbox"][name="UserCheckBox"]', oTable.fnGetNodes()).each( function()
{
$('input[type="checkbox"][name="UserCheckBox"]', oTable.fnGetNodes()).attr('checked','checked');
checkedItems.push($(this).attr('id'));
});
});
$('#UnSelect_All').click(function()
{
$('input[type="checkbox"][name="UserCheckBox"]', oTable.fnGetNodes()).each( function()
{
$('input[type="checkbox"][name="UserCheckBox"]', oTable.fnGetNodes()).attr('checked',false);
});
checkedItems.length = 0; //Make Empty Array
oTable.fnDraw(false); //Reload data table
});
//--End: Select And UnSelect All CheckBoxes
<!--********** Start: Remembering Checkbox checked values ***************-->
var checkedItems = new Array();
// this is needed as we might uncheck items that are checked to begin with
$('input[type="checkbox"][name="UserCheckBox"]', ".datatable").each(function() {
if ($(this).is(':checked'))
{
checkedItems.push($(this).attr('id'));
}
});
// function that can remove items from the array
checkedItemsRemove = function(item) {
var i = 0;
while (i < checkedItems.length) {
if (checkedItems[i] == item) {
checkedItems.splice(i, 1);
} else {
i++;
}
}
}
// function to check if an item is in the array
checkedItemsContains = function(item) {
for (var i = 0; i < checkedItems.length; i++) {
if (checkedItems[i] == item)
return true;
}
return false;
}
// function to set the checked attribute of those which should be on the current table display
persistChecked = function()
{
$('input[type="checkbox"][name="UserCheckBox"]', '.datatable').each(function() {
if (checkedItemsContains($(this).attr('id'))) {
$(this).attr('checked', 'checked');
} else {
//$(this).removeAttr('checked');
}
});
}
<!--On CheckBox Click Event Event-->
$('.datatable').on('click', '.UserCheckBoxC', function (e)
{
if ($(this).is(':checked')) {
checkedItems.push($(this).attr('id'));
} else {
checkedItemsRemove($(this).attr('id'));
}
return true;
});
<!--********** End: Remembering Checkbox checked values ***************-->
<!--********** Start: Data Table server side processing ***************-->
var oTable = $('.datatable').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "gettabledata.php?event=1",
"aaSorting": [[1, "desc"]],
//New Added by pintu on 12/12/2013
"aoColumnDefs": [
//--Code for Hidden Filed Its Guest ID
{ "bSortable": false,"bVisible": false, "aTargets": [0] },
//--Make CheckBoxez Not Shortable
{ "bSortable": false,"sWidth": "50px","aTargets": [1]},
//--Make ID Not Shortable
{ "bSortable": false,"sWidth": "50px","aTargets": [2]},
//--Make Address Not Shortable
{ "bSortable": false,"sWidth": "50px","aTargets": [5]},
//--Make Phone Not Shortable
{ "bSortable": false,"sWidth": "50px","aTargets": [6]},
//---Code For Actions Buttons
{
"bSortable": false,
"sWidth": "200px",
"aTargets":[7],
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol)
{
$(nTd).css('text-align', 'center');
},
"mData": null,
"mRender": function( data, type, full)
{
var returnvar = '';
returnvar = returnvar + '<td><a class="edit" href="javascript:return false;">Edit</a></td><td>&nbsp;</td>';
returnvar = returnvar + '<td><a class="delete" href="javascript:return false;">Delete</a></td>';
return returnvar;
}
}
//---End Code For Actions Buttons
],
//End
"fnDrawCallback": function()
{
persistChecked(); //function call
}
});
<!--********** End: Data Table server side processing ***************-->
// Start: Edit and Delete function for edit record
var nEditing = null;
$('.datatable').on('click', 'a.edit', function (e) {
e.preventDefault();
/* Get the row as a parent of the link that was clicked on */
var nRow = $(this).parents('tr')[0];
if ( nEditing !== null && nEditing != nRow ) {
/* A different row is being edited - the edit should be cancelled and this row edited */
restoreRow( oTable, nEditing );
editRow( oTable, nRow );
nEditing = nRow;
}
else if ( nEditing == nRow && this.innerHTML == "Save" ) {
/* This row is being edited and should be saved */
saveRow( oTable, nEditing );
nEditing = null;
}
else {
/* No row currently being edited */
editRow( oTable, nRow );
nEditing = nRow;
}
});
function editRow (oTable,nRow )
{
var aData = oTable.fnGetData(nRow);
//alert(aData[2]);
var jqTds = $('>td', nRow);
//jqTds[1].innerHTML = '<input value="'+aData[1]+'" type="text">';
jqTds[2].innerHTML = '<input value="'+aData[3]+'" type="text" style="width:150px;">';
jqTds[3].innerHTML = '<input value="'+aData[4]+'" type="text" style="width:150px;">';
jqTds[4].innerHTML = '<input value="'+aData[5]+'" type="text" style="width:150px;">';
jqTds[5].innerHTML = '<input value="'+aData[6]+'" type="text" style="width:100px;">';
jqTds[6].innerHTML = '<a class="edit" href="">Save</a>';
}
function saveRow (oTable, nRow )
{
var aData = oTable.fnGetData(nRow);
var jqInputs = $('input', nRow);
$.post("act_updateguest.php?id="+aData[0]+"&guestName="+jqInputs[1].value+"&guestEmail="+jqInputs[2].value
+"&guestAddress="+jqInputs[3].value+"&guestPhone="+jqInputs[4].value,
function(data)
{
restoreRow(oTable,nRow);
});
}
function restoreRow ( oTable, nRow )
{
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
for (var i=0,iLen=jqTds.length; i<iLen ; i++)
{
oTable.fnUpdate( aData[i], nRow, i, false);
}
oTable.fnDraw(false);
}
<!--Delete Guest From Event-->
$('.datatable').on('click', 'a.delete', function (e) {
e.preventDefault();
var nRow = $(this).parents('tr')[0];
var aData = oTable.fnGetData(nRow);
$("#dialog").dialog({height: 270,width:500,modal: true,
buttons: {
"OK": function()
{
value = $(this).find('input:checked').val();
//alert("GuestID="+aData[0]);
//alert("EventID="value);
$.post("act_deleteguest.php?guestID="+aData[0]+"&eventId="+value,
function(data)
{
restoreRow(oTable,nRow);
});
$(this ).dialog("close");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
// END: Edit and Delete function for edit record
//Start : Invite All Guest dialog
$("#invite_All").click(function()
{
$("#Invitedialog").dialog({height: 270,width:500,modal: true,
buttons: {
"OK": function()
{
var IsText="0";
var IS_MAIL="0";
var IS_CALL="0";
if ($(this).find('input[type="checkbox"][name="SendSMS"]').is(':checked'))
{
IsText = $('input[type="checkbox"][name="SendSMS"]').val();
}
if ($(this).find('input[type="checkbox"][name="SendVoice"]').is(':checked'))
{
IS_CALL = $('input[type="checkbox"][name="SendVoice"]').val();
}
if ($(this).find('input[type="checkbox"][name="SendEmail"]').is(':checked'))
{
IS_MAIL = $('input[type="checkbox"][name="SendEmail"]').val();
}
$.post("act_inviteallguest.php?IS_MAIL="+IS_MAIL+"&IS_TEXT="+IsText+"&IS_CALL="+IS_CALL,
function(data)
{
//alert('Insert ho Gaya');
});
$(this ).dialog("close");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
//End : Invite All Guest dialog
//Start : Invite Selected Guest dialog
$("#invite_selected").click(function()
{
$("#Invitedialog").dialog({height: 270,width:500,modal: true,
buttons: {
"OK": function()
{
var selectedGuests = checkedItems;
if(selectedGuests.length > 0)
{
var IsText="0";
var IS_MAIL="0";
var IS_CALL="0";
if ($(this).find('input[type="checkbox"][name="SendSMS"]').is(':checked'))
{
IsText = $('input[type="checkbox"][name="SendSMS"]').val();
}
if ($(this).find('input[type="checkbox"][name="SendVoice"]').is(':checked'))
{
IS_CALL = $('input[type="checkbox"][name="SendVoice"]').val();
}
if ($(this).find('input[type="checkbox"][name="SendEmail"]').is(':checked'))
{
IS_MAIL = $('input[type="checkbox"][name="SendEmail"]').val();
}
$.post("act_inviteselectedguest.php?IS_MAIL="+IS_MAIL+"&IS_TEXT="+IsText
+"&IS_CALL="+IS_CALL+"&selectedGuests="+selectedGuests,
function(data)
{
//alert('Insert ho Gaya');
});
}
$(this ).dialog("close");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
//End : Invite Selected Guest dialog
});
</script>
<style type="text/css">
body{
width:100%;
}
div.mainContainer{
width:900px;
margin:0 auto;
background-color:#DEF7FE;
}
A:link
{
text-decoration: none;
}
</style>
</head>
<body>
<div class="mainContainer">
<div style='float:right;width:400px;' align='left'>
<a href="javascript:void(0)" id="Select_All" class="link">Select All</a>&nbsp;&nbsp;
<a href="javascript:void(0)" id="UnSelect_All">UnSelectAll</a>&nbsp;&nbsp;
<a href="javascript:void(0)" id="invite_selected">Invite Selected</a>&nbsp;&nbsp;
<a href="javascript:void(0)" id="invite_All">Invite All</a>&nbsp;&nbsp;
</div>
<table class="display datatable" id="aa">
<thead>
<tr>
<th>Hidden</th>
<th></th>
<th>SNo</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Actions</th>
</tr>
</thead>
</table>
<div id="dialog" title="Delete guest" style="display:none;">
Are you sure you want to delete this record?
</div>
<div id="Invitedialog" title="Invite Guests for events." style="display:none;">
<form>
<div style="float:left;margin-top: 0px;vertical-align: top;" align="left">
<input type="checkbox" checked name="SendSMS" id="SendSMS" value="1" style="margin:0 auto"></div>
<div align="left" style="margin-left: 20px;">Send SMS. </div>
<div style="float:left;clear:both;vertical-align: top;" align="left">
<input type="checkbox" checked name="SendVoice" id="SendVoice" value="1" style="margin:0 auto"></div>
<div align="left" style="margin-left: 20px;">Send Voice. </div>
<div style="float:left;clear:both;vertical-align: top;" align="left">
<input type="checkbox" checked name="SendEmail" id="SendEmail" value="1" style="margin:0 auto"></div>
<div align="left" style="margin-left: 20px;">Send Email. </div>
</form>
</div>
</div>
</body>
</html>
view raw checkboxes.php hosted with ❤ by GitHub
<?php
session_start();
$userId = 1;
/*
* Script: DataTables server-side script for PHP and MySQL
* Copyright: 2010 - Allan Jardine
* License: GPL v2 or BSD (3-point)
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array( 'pk_id', 'name_vch', 'email_vch', 'Address_vch', 'phone_vch');
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "pk_id";
/* DB table to use */
$sTable = "Guests2 g2 inner join mycardco_marriage.GUEST_EVENT ge on g2.pk_id = ge.guest_Id";
/* Database connection information */
$gaSql['user'] = "root";
$gaSql['password'] = "pinturp1";
$gaSql['db'] = "mycardco_marriage";
$gaSql['server'] = "127.0.0.1";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* MySQL connection
*/
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}
/*
* Ordering
*/
if (isset( $_GET['iSortCol_0']) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "WHERE customerid_int=".$userId." AND ge.event_id=".$_GET['event'];
if ( $_GET['sSearch'] != "" )
{
$sWhere .= " AND (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
$countRow = $_GET['iDisplayStart'] + 1;
while ($aRow = mysql_fetch_array( $rResult ))
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "pk_id")
{
$row[] = $aRow['pk_id']; //Hidden id for edit or delete
$row[] = "<input type='checkbox' name='UserCheckBox' class='UserCheckBoxC' id='$aRow[pk_id]' value='$aRow[pk_id]'>";
$row[] = $countRow; //For SNO
}
else if ( $aColumns[$i] == "Address")
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[$aColumns[$i] ];
}
}
$output['aaData'][] = $row;
$countRow += 1;
}
echo json_encode( $output );
?>

Comments

Popular posts from this blog

Login with facebook using coldfusion

Create CSV file in Coldfusion Using CFFile

Get Previous One Day Data in Sql Server