I'm trying to pass a php array to JQuery and set a JQuery array to the php array to use as a source for my JQuery DataTable.
Everything seems to run sound, but when the page renders, I only get the header row displayed. Why is my DataTable not displayed?
What changes should I make so that the DataTable displays and renders properly?
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
<th>SalesCurrent</th>
<th>Sales30Days</th>
<th>Sales60Days</th>
<th>Sales90Days</th>
<th>Sales120Days</th>
<th>TotalSales</th>
<th>ErrorDollarAmount</th>
</tr>
</thead>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data); ?>;
$(document).ready(function () {
$('#my-table').dataTable({
data: information,
columns: [
{ title: 'id' },
{ title: 'Name' },
{ title: 'NumOfSales' },
{ title: 'SalesCurrent' },
{ title: 'Sales30Days' },
{ title: 'Sales60Days' },
{ title: 'Sales90Days' },
{ title: 'Sales120Days' },
{ title: 'TotalSales' },
{ title: 'ErrorDollarAmount' }
]
});
});
</script>
</html>
EDIT
I think I see part of the problem, when I view the page source it shows the below, which comments out all of the php EXCEPTthe php that is being written on screen.
<!-- Code Embed v2.3.2 -->
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
$data = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
Here is the working example for passing the data object to datatable using php json_encode() method
Even you were missing the tbody tag for the data table
http://phpfiddle.org/main/code/izyq-3a7y
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<?php
$data = array(
array('id'=>'parvez', 'Name'=>11, 'NumOfSales'=>101),
array('id'=>'alam', 'Name'=>1, 'NumOfSales'=>102),
array('id'=>'phpflow', 'Name'=>21, 'NumOfSales'=>103)
);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data) ?>;
$(document).ready(function () {
console.log(information)
$('#my-table').dataTable({
data: information,
columns: [
{ data: 'id' },
{ data: 'Name' },
{ data: 'NumOfSales' },
]
});
});
</script>
</html>
Changes in your current code should be like below:
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
<th>SalesCurrent</th>
<th>Sales30Days</th>
<th>Sales60Days</th>
<th>Sales90Days</th>
<th>Sales120Days</th>
<th>TotalSales</th>
<th>ErrorDollarAmount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data) ?>;
$(document).ready(function () {
$('#my-table').dataTable({
data: information,
columns: [
{ data: 'id' },
{ data: 'Name' },
{ data: 'NumOfSales' },
{ data: 'SalesCurrent' },
{ data: 'Sales30Days' },
{ data: 'Sales60Days' },
{ data: 'Sales90Days' },
{ data: 'Sales120Days' },
{ data: 'TotalSales' },
{ data: 'ErrorDollarAmount' }
]
});
});
</script>
</html>
Related
I have created a website mainly using HTML, CSS, PHP and MYSQL. I have successfully gotten tabledit working on the site, but I am not sure how to add the functionality for dropdown checkboxes. I need it to show as checked if the user has the role and when unchecked to update the MySQL table. I have tried reading the code, but am not real familiar with jquery, ajax or javascript. Are dropdown checkboxes something that can be implemented with this plugin?
ModifyUser.php
<html>
<head>
<title>Modifying Users</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
<style>
#sample_data tr > *:nth-child(1) {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h3 align="center">Modifying Users</h3>
<br />
<div class="panel panel-default">
<!-- <div class="panel-heading">Sample Data</div>-->
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Approval</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br />
<br />
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#sample_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"FetchUserTable.php",
type:"POST"
}
});
$('#sample_data').on('draw.dt', function(){
$('#sample_data').Tabledit({
url:'ActionUserTable.php',
dataType:'json',
columns:{
identifier : [0, 'user_id'],
editable:[
[1, 'first_name'],
[2, 'last_name'],
[3, 'email'],
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}']
[5, 'role_id'] // THIS SHOULD BE AN EDITABLE DROPDOWN CHECKBOX
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#' + data.id).remove();
$('#sample_data').DataTable().ajax.reload();
}
}
});
});
});
</script>
FetchUserTable.php
<?php
//FetchUserTable.php
require_once("SetDBConnection.php");
$column = array("user_id", "first_name", "last_name", "email", "admin_approved", "role_id");
$query = "SELECT users.user_id, users.first_name,
users.last_name, users.email,
users.admin_approved,
users_roles.role_id
FROM users, users_roles GROUP BY user_id;";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE first_name LIKE "%'.$_POST["search"]["value"].'%"
OR last_name LIKE "%'.$_POST["search"]["value"].'%"
OR email LIKE "%'.$_POST["search"]["value"].'%"
OR admin_approved LIKE "%'.$_POST["search"]["value"].'%"
OR role_id LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY user_id ASC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor(); // Added
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['user_id'];
$sub_array[] = $row['first_name'];
$sub_array[] = $row['last_name'];
$sub_array[] = $row['email'];
$sub_array[] = $row['admin_approved'];
$sub_array[] = $row['role_id'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT users.user_id, users.first_name,
users.last_name, users.email,
users.admin_approved,
users_roles.role_id
FROM users, users_roles GROUP BY user_id;";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
i want to use the tableedit JQuery Plugin. This is a code example. The edit of the table is working. But the delete doesnt work. I get the error:
Tabledit Ajax fail => parsererror : SyntaxError: Unexpected token < in JSON
I dont understand why. I have read some Posts here, but I have the Problem yet.
Here is my code:
<?php
$connect = mysqli_connect("localhost", "root", "root", "testing");
$query = "SELECT * FROM tbl_user ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<html>
<head>
<title>Live Table Data Edit Delete using Tabledit Plugin in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery.tabledit.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Data Edit Delete using Tabledit Plugin in PHP</h3><br />
<table id="editable_table" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["firstname"].'</td>
<td>'.$row["lastname"].'</td>
</tr>
';
}
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#editable_table').Tabledit({
url:'action.php',
columns:{
identifier:[0, "id"],
editable:[[1, 'firstname'], [2, 'lastname']]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#'+data.id).remove();
}
}
});
});
</script>
<?php
//action.php
$connect = mysqli_connect('localhost', 'root', 'root', 'testing');
$input = filter_input_array(INPUT_POST);
$firstname = mysqli_real_escape_string($connect, $input["firstname"]);
$lastname = mysqli_real_escape_string($connect, $input["lastname"]);
if($input["action"] === 'edit'){
$query = "
UPDATE tbl_user
SET firstname = '".$firstname."',
lastname = '".$lastname."'
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
if($input["action"] === 'delete'){
$query = "
DELETE FROM tbl_user
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
header('Content-type: application/json');
print_r(json_encode($input));
?>
What I want to be able to do:
I have a page setup so that a table is populated with values from the database. I also generate a button for each of the rows on the table. The button is connected to the database to a field called status. It is initially at 0. When the button is clicked, I want to be able to update this value by incrementing it by 1.So after the button is clicked on the webpage, the database status value is incremented by 1.
I have tried using AJAX for this, but I havent seemed to have much luck.
view.php (Where the table is populated from the database)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<?php
include 'php/connect.php';
include 'php/status.php';
function getStatus($num){
$status = "";
switch ($num) {
case ($num == 0):
$status = "Pending";
case ($num == 1):
$status = "Completed";
default:
$status = "Pending";
}
return $status;
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 center-block">
<h1>View the Commissions</h1>
<div class="panel panel-default">
<div class="panel-heading">Commissions</div>
<div class="panel-body">
<p></p>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Alias</th>
<th>Description</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect, "SELECT * FROM orders") or die(mysql_error());
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<th scope=\"row\">";
echo $row['orderID'];
echo "</th>";
echo "<th>".$row['alias']."</th>";
echo "<th>".$row['description']."</th>";
echo "<th>$".$row['price']."</th>";
echo "<th><button type=\"button\" class=\"btn btn-default btn-info\" name=\"" .$row['orderID']. "\">".getStatus($row['status'])."</button></th>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
</html>
As you can see, for each row in the database the table is populated. Here is an image of the webpage:
I did have this code for the AJAX. It did give me the correct output in the console of the browser, but I wasnt able to get this value into the process.php page
$.ajax({
url: 'php/process.php',
type: 'POST',
data: {
orderID: obj.id
},
success: function (data) {
console.log(data);
}
});
How would I have it so that as soon as the button is clicked, it updates the value and refreshes the page. Any help would be greatly appreciated
TLDR; When I click the "Pending" button, a value in the database is incremented by 1.
Your getStatus() function didn't have break statement. for simple POST use $.post. I have added .status class to your button to use it as selector with jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<?php
include 'php/connect.php';
include 'php/status.php';
// fixed this function by adding break and removing $num from case statement
function getStatus($num)
{
$status = "";
switch ($num) {
case 0:
$status = "Pending";
break;
case 1:
$status = "Completed";
break;
default:
$status = "Pending";
}
return $status;
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 center-block">
<h1>View the Commissions</h1>
<div class="panel panel-default">
<div class="panel-heading">Commissions</div>
<div class="panel-body">
<p></p>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Alias</th>
<th>Description</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect, "SELECT * FROM orders") or die(mysql_error());
while ($row = mysqli_fetch_array($query)) : ?>
<tr>
<th scope="row"><?php echo $row['orderID']; ?></th>
<th><?php echo $row['alias']; ?></th>
<th><?php echo $row['description']; ?></th>
<th><?php echo $row['price']; ?></th>
<th>
// added .status class here
<button type="button" class="btn btn-default btn-info status"
name="<?php echo $row['orderID']; ?>"><?php echo getStatus($row['status']); ?></button>
</th>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
// the AJAX for updating the status
$('.status').on('click', function () {
var id = $(this).attr('name');
var btn = $(this);
$.post('php/process.php', {orderId: id}, function (response) {
var res = JSON.parse(response);
if (res.results == true) {
btn.html('Completed');
}
})
})
</script>
</html>
In php/process.php
<?php
include 'php/connect.php';
if (isset($_POST['orderId'])) {
$orderId = $_POST['orderId'];
$sql = "UPDATE `orders` SET `status`= 1 WHERE `orderID` = $orderId";
if (mysqli_query($connect, $sql)) {
echo json_encode(['results' => true]); // when update is ok
}else {
echo json_encode(['results' => false]); // when update fail
}
}
So, I think I may be in over my head. I've looked around on here for a quite some time but have not been able to find something that will help me.
I am trying to build a display order from, similar to what you would see in a restaurant or fast food, that automatically and smoothly updates when a new entry has been entered into the MySQL table.
I tryed using AJAX but I could not get it to work
Main PHP page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/fulfillment.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<div class="container">
<h1>Orders</h1>
<p>Area that displays all of the active and past orders.</p>
<div align="right">
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-on="Active" data-off="Past">
</div>
<!-- Active Orders -->
<?php
include '../connect.php';
//get information form tblOrder
$sql = "SELECT * FROM tblOrder WHERE Filled=0";
$result = $db->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
<!-- Build the table -->
<h2>Active</h2>
<table ID = "myTable" class="table table-striped">
<thead>
<tr>
<th>Order Number</th>
<th>User ID</th> <!-- will turn to user name later down the road -->
<th>Food</th>
<th>Pick Up Time</th>
<th>Filled</th>
</tr>
</thead>
<tbody>
<?php
// run though tblOrders
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//assign all of the values
$OrderNumber = $row["Order_Number"];
$FoodID = $row["F_ID"];
$DrinkID = $row["D_ID"];
$UserID = $row["User_ID"];
$Filled = $row["Filled"];
$RequestTime = $row["Request_Time"];?>
<!-- out put each line of the value -->
<tr>
<td><?php echo $OrderNumber; ?></td>
<td><?php echo $UserID; ?></td> <!-- switch to name once it is avalible ->
<td><!-- put food order here --></td>
<td><?php echo $RequestTime; ?></td>
<td><input type="button" class="btn btn-default" value="Complete"onclick="toPast(this, <?php echo $OrderNumber?>)"/></td>
</tr>
<?php
}
}
//close the data connection
$db->close();
?>
</tbody>
</table>
JavaScript
function toPast(btn, ONum) {
var dataString = 'OrderNumber=' + ONum + '&UpdateNumber=' + '1';
$.ajax({
type: "POST",
url: "update_sucess.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
}
Could anyone point me in the right direction or know someplace has a "how-to" on how to do this that I could read?
I have two files php (gettable.php and index.php) the index file display the result obtained by gettable.php every one seond, I want update the content of my table dynamically in the index (only new or changed value must be changed) using ajax, I am beginner in ajax.
Help me please
thank you
gettable.php
//
//
// I load data from the server(xml file)
$xml = simplexml_load_string($result);
foreach($xml as $node)
{
$name = "";
$value = -1;
foreach($node->attributes() as $a => $b) {
if($a == "name")
{
$name = (string)$b;
}
else if($a == "value")
{
$value = (string)$b;
}
}
$vars[$name] = $value;
}
?>
<table border="1">
<tr>
<th>id</th>
<th>abc</th>
<th>def</th>
</tr>
<tr>
<td><?php
echo "<p>x: ".$vars["x"]."</p>";
?>
</td>
<td><?php
echo "<p>y: ".$vars["y"]."</p>";
?>
</td>
<td><?php
echo "<p>z: ".$vars[z"]."</p>";
?>
</td>
</tr>
</table>
file index.php
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script language="JavaScript">
$('#data').load("gettable.php");
setInterval( "SANAjax();", 1000 );
$(function() {
SANAjax = function(){
$('#data').load("gettable.php");
}
});
</script>
</head>
<body>
<div id="data">
<?php include_once('gettable.php'); ?>
</div>
</body>
The script code should like this
$(function(){
function loadData(){
$('#data').load("gettable.php");
}
setInterval(function() { loadData(); }, 1000 );
});