Passing of data from main page to php query inside a modal - javascript

I have a dataTable that passes it's row to a modal. Will it be possible to pass it directly to the php page using the same modal script?
This is my main_page.php
<table id="example1" class="table table-bordered">
<thead>
<th>Reference No</th>
<th>Finger Scan No</th>
<th>Date From</th>
<th>Date To </th>
<th>Tools </th>
</thead>
<tbody>
<?php
$user = $user['fingerscanno'];
$sql = "
SELECT
payroll.payrollno AS payrollno,
payroll.referenceno AS referenceno,
payroll.fingerscanno AS fingerscanno,
payroll.datefrom AS datefrom,
payroll.dateto AS dateto,
USERINFO.USERID,
USERINFO.BADGENUMBER
FROM
payroll,
USERINFO
WHERE
USERINFO.BADGENUMBER = payroll.fingerscanno AND
payroll.fingerscanno='$user'
";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['referenceno']."</td>
<td>".$row['fingerscanno']."</td>
<td>".$row['datefrom']."</td>
<td>".$row['dateto']."</td>
<td>
<button class='btn btn-success btn-sm edit btn-flat' data-id='".$row['referenceno']."'><i class='fa fa-edit'></i> Proof of Attendance</button>
<button class='btn btn-danger btn-sm delete btn-flat' data-id='".$row['referenceno']."'><i class='fa fa-edit'></i> Payslip Summary</button>
</td>
</tr>
";
}
?>
</tbody>
</table>
<?php include 'includes/mymodal.php'; ?>
This is the modal function
$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
This is the modal page
mymodal.php
<div class="modal fade" id="edit">
<input type="hidden" class="decid" id="id" name="id">
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
<?php
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
";
}
?>
</tbody>
</table>
</div>
My question is, how will I pass this into the table? So that the variable referenceno='$id' will receive the value from the main page.

You need to use AJAX.
Ajax is a javascript methodology that allows you to exchange information with a back-end PHP file, just as you are attempting to do.
The AJAX code block will send data to the mymodal.php file, the mymodal.php file will do the MySQL lookup and create the HTML, then echo a string variable (which could be a json object or it could be the HTML that you built in your while loop) back to the main page. The AJAX code block will receive the data echo'd out from the PHP file inside the .done() function and, also in that function, you can modify the DOM to inject the new data. To the user, it will look like they clicked on an element with class edit and the data just appeared in the modal.
Note that you do not include the mymodal.php file in your main_file.php page, because the AJAX code block knows how to communicate with that file.
You will need to add the HTML structure for the modal to the bottom of your main page (note that it is initially set to display:none):
<style>
#lamodal{display:none;position:fixed;width:100vw;height:100vh;background:black;opacity:0.8;}
#mdl_inner{width:60%;height:40%;}
.myflex{display:flex;align-items:center;justify-content:center;}
</style>
<div id="lamodal" class="myflex">
<div id="mdl_inner"></div>
</div><!-- #lamodal -->
Your javascript (AJAX) will look something like this:
$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'mymodal.php',
data: 'userid=id'
}).done(function(d){
//console.log('d: '+d);
$('#mdl_inner').html(d);
$('#lamodal').show();
});
});
});
Your mymodal.php file would be changed to look like this:
<?php
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$out = '
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
';
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$out .= '
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
';
}
$out .= '
</tbody>
</table>
';
echo $out;
?>
Note how we are constructing a string variable and building it through concatination. When done, just echo $out and the newly-constructed HTML will appear in the .done() function of your AJAX code block.
See these additional AJAX examples and explanations:
http://www.jayblanchard.net/basics_of_jquery_ajax.html
Simple Like/Unlike text button - adding ajax etc
pass var to bootstrap modal where php will use this value

Related

datatable with child rows using mysql

In MySQL Database, I have two tables Abc and Pqr. In Abc table there's a unique ID, that ID is used in Pqr table as foreign key.
I want to show the parent element as Abc table data and child rows as Pqr table data with respect to Abc unique ID.
Here is my code:
$sqlGetParents="SELECT * from projectrera order by project_id";
$resultGetParents = $conn->query($sqlGetParents);
?>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Project Name</th>
<th>Builder Id</th>
<th>Location Id</th>
<th>Phase</th>
<th>Status</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($resultGetParents)) {
echo " <tr>
<td class='details-control'></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
} ?>
</table>
<div id="test">
<table id='example1'>
<?php
$sqlGetCatWithParent1="SELECT * from info";
$resultGetCatWithParent1 = $conn->query($sqlGetCatWithParent1);
while ($row3 = mysqli_fetch_array($resultGetCatWithParent1)) {
echo " <tr>
<td></td>
<td>".$row3[1]."</td>
<td>".$row3[2]."</td>
<td>".$row3[3]."</td>
</tr>";
}
?>
Why don't you use the JOIN or Subquery on your select statement? I think that would help you since you're using a relational schema on your tables.
Example:
$sqlGetParents =
SELECT abc.*, pqr.* from projectrera abc
LEFT JOIN info pqr on pqr.project_id = abc.project_id
order by project_id
In your HTML table, I suggest to use FOREACH instead of WHILE.
<?php foreach ($row->result() in $resultGetParents) {
echo "<tr>
<td class='details-control'></td>
<td>".<?php echo $row[1]."</td>
<td>".$row[1]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
echo "<tr>
<td></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
</tr>";
} ?>
You can change the $row number based on the results or use text to easily know which columns should be displayed on your table. (i.e $row['project_id'])

Jquery Data table Error when i add a search function

I am having a problem with my jQuery DataTable, my data table is working when I only have four columns for my search function. I have 7 columns on my table but when I try to add another column to my search function, I have this message:
DataTables warning: table id=example - Invalid JSON response. For more
information about this error, please see http://datatables.net/tn/1
This is the code for my table
<div class="container" id=subwrapper>
<h1>Employee's Data Table</h1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Employee ID</th>
<th>First name</th>
<th>Last name</th>
<th>Birthday</th>
<th>Age</th>
<th>Job Position</th>
<th>Contact number</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Employee ID</th>
<th>First name</th>
<th>Last name</th>
<th>Birthday</th>
<th>Age</th>
<th>Job Position</th>
<th>Contact number</th>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function(){
var dataTable=$('#example').DataTable({
"processing": true,
"serverSide":true,
"ajax":{
url:"fetchemployee.php",
type:"post"
}
});
});
</script>
My PHP code:
<?php
$con=mysqli_connect('localhost','root','','projectmanagementdb')
or die("connection failed".mysqli_errno());
$request=$_REQUEST;
$col =array(
0 => 'employeeID',
1 => 'employeeFirstname',
2 => 'employeeLastname',
3 => 'employeeBirthday',
4 => 'employeeAge',
5 => 'employeePosition',
6 => 'employeeContactnumber'
); //create column like table database
$sql ="SELECT * FROM employeeinfo";
$query=mysqli_query($con,$sql);
$totalData=mysqli_num_rows($query);
$totalFilter=$totalData;
//Search function of Jquery Data table
$sql ="SELECT * FROM employeeinfo WHERE 1=1";
if(!empty($request['search']['value'])){
$sql.=" AND (employeeID Like '".$request['search']['value']."%' ";
$sql.=" OR employeeFirstname Like '".$request['search']['value']."%' ";
$sql.=" OR employeeLastname Like '".$request['search']['value']."%' ";
$sql.=" OR employeeBirthday Like '".$request['search']['value']."%' )";
$sql.=" OR employeeAge Like '".$request['search']['value']."%' )";
$sql.=" OR employeePosition Like '".$request['search']['value']."%' )";
$sql.=" OR employeeContactnumber Like '".$request['search']['value']."%'
)";
}
$query=mysqli_query($con,$sql);
$totalData=mysqli_num_rows($query);
$data=array();
while($row=mysqli_fetch_array($query)){
$subdata=array();
$subdata[]=$row[0]; //employeeID
$subdata[]=$row[1]; //employeeFirstname
$subdata[]=$row[2]; //employeeLastname
$subdata[]=$row[3]; //employeeBirthday
$subdata[]=$row[4]; //employeeAge
$subdata[]=$row[5]; //employeePosition
$subdata[]=$row[6]; //employeeContactnumber
$data[]=$subdata;
}
$json_data=array(
"draw" => intval($request['draw']),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFilter),
"data" => $data
);
echo json_encode($json_data);
?>

Fetch table row data as per the selected checkbox

I am using Material Design Lite to create a table and I am inserting rows dynamically using php.
The material design lite has provided checkboxes for each row. Now, I want to use the selected row's data on a button click. Does anyone have any idea how to do that?
Here is the code :
<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp" id="sanctionedTable">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Name</th>
<th class="mdl-data-table__cell--non-numeric">Registration No.</th>
<th class="mdl-data-table__cell--non-numeric">Amount</th>
</tr>
</thead>
<tbody>
<?php
$temp = "";
while($row = mysqli_fetch_assoc($result))
{
$temp="<tr><td>".$row["name"]."</td><td>".$row["regno"]."</td><td>".$row["amount"]."</td></tr>";
echo $temp;
}
?>
</tbody>
</table>
You can use something like this using jquery:
$('tr').click(function(){
alert("Name:"+$(this).children('td:nth-child(1)').html()+",Registration nio:"+$(this).children('td:nth-child(2)').html()+",Amount:"+$(this).children('td:nth-child(3)').html());
});
This fetches the information in each row.

How to fetch the data for one page at a time

I have the problem to fetch the as per number of rows at a time in jQuery DataTables with Bootstrap. Firstly, my code below fetches whole data from the database and starts the pagination.
But I want data loaded for one page at a time.
My PHP code is:
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th> Name</th>
<th>category</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<?php foreach ($datastat as $row) {
?>
<tr>
<td><?php echo $row['fname'];?> <?php echo $row['mname'];?> <?php echo $row['lname'];?></a></td>
<td><?php echo $row['category'];?></td>
<td><?php echo $row['location'];?></td>
</tr>
<?php }?>
</tbody>
<tfoot>
<tr>
<th> Name</th>
<th>category</th>
<th>Location</th>
</tr>
</tfoot>
</table>
My javascript code is:
$(function() {
$('#example1').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"pageLength": 10
});
});
You need to implement server-side processing in order to retrieve one page at a time from the server, see this example.
Luckily DataTables distribution includes PHP class ssp.class.php and sample code that makes it fairly easy to use with PHP.

checkbox in paginated datatable

I have a datatable and buttons for delete and update. And these button are disabled. I also have some checkbox in the first column of every row. Whenever I click the checkbox, the edit and delete button will be enabled. It is working on the first page of my datatable but when I click a row from other pages of the datatable, it doesn't enabling the buttons. What is the problem with it? I have this code:
HTML Table:
<table class="table table-bordered table-hover table-striped" id="account_data" width="100%" style="margin-top: 0px"> <thead class="header">
<tr class="well"><th colspan="3" style="text-align:center">LIST OF USERS</th></tr>
<tr class="well">
<th style="width: 5px"><input type="checkbox" class="check"/></th>
<th style="font-size: 14px;padding-left: 20px;"> ID#</th>
<th style="font-size: 14px;padding-left: 20px;"> Name</th>
</tr>
</thead>
<tbody>
<?php if($users != NULL){?>
<?php foreach($users as $row){ ?>
<tr>
<td align="center"><input type="checkbox" class="accounts" name="accounts[]" value="<?php echo $row->user_id;?>"/></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->user_id;?></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->user_name;?></td>
</tr>
<?php }?>
<?php }?>
</tbody>
</table>
JQUERY:
<script>
$(document).ready(function(){
var count=0;
var chkId=new Array();
var checkedValue ='';
$('.check').click(function() {
$(" .check").each(function () {
if($(this).is(":checked"))
{
$(" .accounts").prop('checked',true);
// $('#edit_acc').prop('disabled',false);
var n = $( " .accounts:checked" ).length;
if(n==1){
$('#edit_acc').prop('disabled',false);
}
if(n>1){
$('#edit_acc').prop('disabled',true);
}
$('#delete_acc').prop('disabled',false);
return
}
$(" .accounts").prop('checked',false);
$('#edit_acc').prop('disabled',true);
$('#delete_acc').prop('disabled',true);
});
});
});
</script>
The problem is that the checkboxes on page #2 and forth not is part of the DOM when your $(document).ready() is fired. jQuery dataTables inject and remove rows in order to show different pages.
So you must use a delegated event handler instead of click(). By that, dynamically injected rows (i.e their checkboxes) also will be included :
$('#account_data').on('click', '.check', function() {
...
});
instead of $('.check').click(function() {

Categories