Data table Server side Ajax Pagination - javascript

I Have A location Table with nearly 14 thousand records,
I need ajax pagination with server-side data.
I used the Below Code But not working.
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
?>
</tbody>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
By Using this Code I am getting error Msg "DataTables warning: table id=htmltableID - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3" and "DataTables warning: table id=htmltableID - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"

You should have below type of code in main file. Let's say Maindata.php
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
And the data(json) needs to be fetch from other file, let's say loadrecords.php(In your case it was location/loadRecord)
<?php
// $data is the list of records fetched from database
// No need to print the data since we need to provide json data to dataTable, so Below code not required
/*
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
*/
// Data which you needs to send in 'location/loadRecord' should be like this (In my case it was `loadrecords.php`)
/*{
"data": [
["1","Location 1","City 1","State 1"],
["2","Location 2","City 2","State 2"],
.....
.....
["N","Location N","City N","State N"]
]
}*/
// Loop the data records fetched from database and prepare array in below format
$json_arr = array(
"data" => array(
array("1","Location 1","City 1","State 1"),
array("2","Location 2","City 2","State 2"),
...............
...............
array("N","Location N","City N","State N"),
)
);
echo json_encode($json_arr);
data will have N no.of rows with 4 columns since you want to display 4 columns in the table so related data needs to be provided in json

Related

how to display a table based on a column value (CSV Path)

I have a table as such
File Name
File path
MyFile1.csv
D:\tmp\MyFile1.csv
MyFile2.csv
D:\tmp\MyFile1.csv
So Far , i'm displaying my main table as such
<div class="panel-body table-responsive">
<table class="table table-striped table-bordered" id="example">
<thead>
<tr style="background-color:#555;color:white;">
<th>File Name</th>
<th>File path</th>
</tr>
</thead>
<tbody>
<?php
$query_table = "select File_Name as File_Name, file_path as file_path from table_logs ";
$result_table = pg_query($dbconn1, $query_table) or die('Échec de la requête : ' . pg_last_error());
while ($list_table = pg_fetch_assoc($result_table)) {
echo '<tr><td>' . $list_table['File_Name '] . '</td><td>' . $list_table['file_path '] . '</td></tr>';
}
?>
</tbody>
<tfoot>
<tr>
<th>File Name</th>
<th>File path</th>
</tr>
</tfoot>
</table>
</div>
To access the csv files a transform them dynamicaly to sub tables based on the file paths i'm using this php code and that working fine
<?php
$query_table = "select File_Name as File_Name, file_path as file_path from table_logs";
$result_table = pg_query($dbconn1, $query_table) or die('Échec de la requête : ' . pg_last_error());
while ($list_table = pg_fetch_assoc($result_table)) {
echo "<br><html><body><table >\n\n";
$f = fopen($list_table['file_path'], "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
?>
My output is as such for the file path 1 : D:\tmp\MyFile1.csv
Key
Value
key1
value1
key2
value2
My output is as such for the file path 2 : D:\tmp\MyFile2.csv
Key
Value
key1
my row 1
key2
my row 2
My question is how display a table when clicking on the value of a File Path
Do i have to add a button the main table ?
How could i achieve the link between the main table and the sub tables ?
How to use ajax to pass the variable and display in Javascript the result ?
You can use an anchor tag for that and pass the filename with your link than grab it from the URL and show data of that file. You can get your filename when people click on your file paths.
D:\tmp\MyFile1.csv
<br>
<?php echo isset($_GET['fileanme']) && $_GET['fileanme'] ? $_GET['fileanme'] : '' ?>

How to retrieve data from mysql in html by calling a function?

I'm trying to retrieve data from MySQL and place it in HTML by calling a function, the PHP conf works fine when open in the browser. But when trying to call, nothing happens. I can't understand what's wrong, tried google it for solutions, but nothing actually works.
here is my PHP code
<?php
include("conn.php");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect: " . mysqli_connect_error();
}
mysqli_select_db($con, "users");
$result = mysqli_query($con, "SELECT * FROM drivers");
echo "<table border='1'>
<tr>
<th>id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>" . $row['lastName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
and here is my ajax calling
<script type="text/javascript" src = "jquery-3.5.1.min.js">
$(document).ready(function (){
$("#show").click(function(){
$.ajax({
type: "POST",
url: "connection.php",
async: false,
dataType: "html",
success: function(response){
$("#container").html(response);
}
});
});
});</script>
Please try this:
$("#show").click(function(){
$.ajax({
type: "POST",
url: "connection.php",
async: false,
dataType: "html",
success: function(response){
$("#container").html(response);
}
});});

How do I create a link in <tr> using the same data requested from an SQL database?

I am trying to create a table which pulls data from an SQL database and each row on the table is a clickable link to it's corresponding page depending on the first column data in the database.
I have managed to do both parts separately i.e create a table with SQL data and i've managed making a table with each row a clickable link however I am struggling to combine the two.
I am using a .js to listen for clicks and send you off depending on the "tr data-href='url'".
My php script to create the table form SQL data creates the "tr" first, then populates the row with each cell, closes the "/tr" and repeats for all rows.
How can I make the php write the "tr data-href='url'" where 'url' is the same as the first column of data for each row?
My PHP script is below, followed by the five lines of JS.
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$db_name = "FFD";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,name,location,plots,blurb FROM Sites");
$all_property = array(); //declare an array for saving property
//showing property
echo '
<div class="content-container">
<h1>Table heading</h1>
<section>
<div class="tbl-header">
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . '</th>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>
</thead>
</table>
</div>
<div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>';
//end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo '</tbody></table></div></section></div>';
?>
$(document).ready(function(){
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
});
I could just be thick and missing something simple and obvious.
Thanks in advance!
You can concatenate your url, like this (assuming id is the column with the url)
while ($row = mysqli_fetch_array($result)) {
echo '<tr data-href="' . $row['id'] . '">';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}

Nested DataTables with non-AJAX data source

I got the following code with bootstrap collapse, but I need a sorting option. Because of this issue I would like to solve my problem with a DataTables. Is there an option to solve my problem without using ajax? I want to fill the parent table and the child by a sql query.
Like this example
<?php
$switches = $pdo->prepare("Select d.name AS 'Hostname', GROUP_CONCAT(DISTINCT v.id ORDER BY v.id ASC SEPARATOR ' / ') AS 'VLAN', GROUP_CONCAT(DISTINCT v.name ORDER BY v.name ASC SEPARATOR ' / ') AS 'Location'
FROM device d
INNER JOIN vlan v ON d.deviceId = v.deviceId
GROUP BY d.name");
$result = $switches->execute();
$count = 0;
while ($row = $switches->fetch()) {
echo '<tr class="accordion-toggle">';
echo '<td><button class="btn btn-default btn-xs collapsed" data-toggle="collapse" data-target="#' . ++$count . '"></button></td>';
echo "<td>" . $row['Hostname'] . "</td>";
echo "<td><a>" . $row['VLAN'] . "</a></td>";
echo "<td>" . $row['Location'] . "</td>";
echo '<td>
<select class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</td>';
echo "</tr>";
echo "<tr>";
echo '<td colspan="12" class="hiddenRow"><div class="accordian-body collapse" id=' . $count . '>';
echo '<table class="table table-striped">';
echo "<thead>";
echo '<tr><p>Interface IP</p>';
echo "</tr>";
echo "<tr>";
echo "<th>Hostname</th>";
echo "<th>phys. Port</th>";
echo "<th>Port Type</th>";
echo "<th>VLAN</th>";
echo "<th>Destination Hostname</th>";
echo "<th>Destination Port</th>";
echo "<th>Tagged</th>
</tr>";
echo "</thead>";
echo "<tbody>";
$statement = $pdo->prepare("SELECT a.physikalischerPort as 'phys. Port', a.logischerPort as 'log. Port', pt.type as 'Port Type', GROUP_CONCAT(v.id ORDER BY v.id ASC SEPARATOR ' / ') as VLAN, d2.name as 'Destination Hostname', b.physikalischerPort as 'Destination Port', pt.tagged as 'Tagged'
FROM port a
inner JOIN port b ON a.portId = b.destinationPortId
INNER JOIN device d ON d.deviceId = a.deviceId
INNER JOIN device d2 ON d2.deviceId = b.deviceId
INNER JOIN porttype pt ON pt.porttypeId = a.porttypeId
INNER JOIN vlan v ON v.portId = a.portId
WHERE a.portId = b.destinationPortId AND b.portId = a.destinationPortId AND a.deviceId = '" . $count . "'
GROUP BY a.logischerPort, a.physikalischerPort,d2.name, b.physikalischerPort, pt.type, pt.tagged
ORDER BY (a.physikalischerPort +0) ASC");
$result = $statement->execute();
while ($row = $statement->fetch()) {
echo "<tr>";
echo "<td>" . $row['phys. Port'] . "</td>";
echo "<td>" . $row['log. Port'] . "</td>";
echo "<td>" . $row['Port Type'] . "</td>";
echo "<td>" . $row['VLAN'] . "</td>";
echo "<td>" . $row['Destination Hostname'] . "</td>";
echo "<td>" . $row['Destination Port'] . "</td>";
echo ($row['Tagged'] == '0') ? '<td><i class="glyphicon glyphicon-remove"></i></td>' : '<td><i class="glyphicon glyphicon-ok"></i></td>';
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "</div>";
echo "</td>";
echo "</tr>";
}
?>
With result:
Result
Ajax is not a mandatory source to populate your DataTable, it is only (widely preferred) option that allows you to keep your data up to date without reloading page (e.g. upon editing certain entries or deleting them).
What you need to do is a PHP-script that will echo simple HTML page that has all the necessary prerequisites (including jQuery and DataTables javascripts and stylesheets) referred within <head> section and empty <table id="mytable"></table> within page <body>.
In addition to above prerequisites, you need to refer in your page HTML to dynamically created javascript that uses arrays of objects (obtained from SQL queries) as DataTables source for both parent and child rows:
<?php
/* query your database over here and put the result into associative arrays,
turn them into JSON-compliant arrays/objects */
$parentSource = ... //PHP variable that contains JSON for parent rows
$childSource = ... //PHP variable that contains JSON for child rows
$js = <<<JS
$(document).ready(function () {
const parentData = ${$parentSource};
const childData = ${$childSource};
const dataTable = $('#mytable').DataTable({
sDom: 't',
data: parentData,
columns: [
{title: 'Hostname', data: 'hostname'},
{title: 'VLAN', data: 'vlan'},
{title: 'Location', data: 'location'},
],
});
//prepare child DataTable upon clicking parent row
$('#mytable').on('click', 'tr', function(){
const parentRow = dataTable.row($(this));
parentRow.child.isShown() ?
parentRow.child.remove() :
parentRow.child('<table id="details"></table>').show();
$(this).toggleClass('shown');
if(!parentRow.child.isShown()) return;
const detailsData = childData[parentRow.data().hostname];
$('#details').DataTable({
sDom: 't',
data: detailsData,
columns: [
{title: 'Hostname', data: 'hostname'},
{title: 'Port', data: 'port'},
{title: 'Port type', data: 'porttype'},
{title: 'VLAN', data: 'vlan'},
{title: 'Destination host', data: 'dsthost'},
{title: 'Destination port', data: 'dstport'},
]
});
});
});
JS;
/* here should go the code to insert above JS code as a <script>
into your page */
?>
Hopefully, I've made my point clear despite of possible PHP blunders (since I haven't been using PHP for a while).
You may find working demo over here.

Javascript not working in AJAX response

Below code is the AJAX response to another page. I have added onclick event to table row and written javascript code to handle it. But javascript code doesn't work.Is this wrong way of coding or there is any problem in code. Suggest me a simple solution
<?php
echo '<script type=\"text/javascript\">
function clicked(){
alert("I am an alert box!");
}
</script>';
$q = $_GET['q'];
include 'db_connect.php';
$sql="SELECT name,address,mobile,email,pan,tan FROM client WHERE name = '$q'";
$sql_bill="SELECT clientname,financialyear,receiptno,amount,ddate,type,chequeno,category FROM billing WHERE clientname = '$q'";
$sql_total="SELECT SUM(amount) AS TotalAmount FROM billing";
$result = mysql_query($sql);
$result_bill = mysql_query($sql_bill);
$result_total = mysql_query($sql_total);
$total= mysql_fetch_array($result_total);
echo "<h4><b>Client details</b></h4><table align='center' border='2'>
<tr>
<th>Name</th>
<th>Address</th>
<th>Mobile</th>
<th>Email</th>
<th>PAN</th>
<th>VAT TIN</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['pan'] . "</td>";
echo "<td>" . $row['tan'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h4><b>Payment received details</b></h4><table align='center' border='2'>
<tr>
<th>Client Name</th>
<th>Financial Year</th>
<th>Receipt No</th>
<th>Date</th>
<th>Type</th>
<th>Chequeno</th>
<th>Category</th>
<th>Amount</th>
</tr>";
while($row = mysql_fetch_array($result_bill))
{
echo "<tr onclick=\"clicked()\">";
echo "<td>" . $row['clientname'] . "</td>";
echo "<td>" . $row['financialyear'] . "</td>";
echo "<td>" . $row['receiptno'] . "</td>";
echo "<td>" . $row['ddate'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['chequeno'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td colspan=7>Total</td>";
echo "<td>".$total['TotalAmount']. "</td>";
echo "</tr>";
echo "</table>";
?>
Try this instead of your script code:
echo <<<EOD
<script type="text/javascript">
function clicked(){
alert("I am an alert box!");
}
</script>
EOD;
Edit 1:
Look in the console (F12), What happens when you click on a tr?
The following fiddle replicates your code and works:
http://jsfiddle.net/Yaj44/
Edit 2:
I think it has something to do with the way you call the data.
Put the function in your main page,
then call the AJAX.
Set innerHTML of specific div with responseData.
If you do it in that order, it might work.
Your way to adding this functionality is very dirty..
If you use JQuery, you can add on the end:
$('tr').click(function() {
alert('Do something on click!');
});
mysql_fetch_array is outdated, use mysqli (or PDO) instead.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();

Categories

Resources