I want to refresh the jquery datatable every 3 seconds. I already done this but I have pagination issues. When I execute the code the pagination is gone so all the data is display without pagination.
Here is my code:
<div id="timexx">
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
<?php
include('../dist/includes/dbcon.php');
$query=mysqli_query($con,"SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC")or die(mysqli_error());
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
?>
<tr>
<td>
<?php echo $id;?>
</td>
<td>
<?php echo $name;?>
</td>
</tr>
<?php }?>
</table>
</div>
And this is my javascript code:
$(document).ready(function() {
setInterval(function() {
$('#timexx').load(location.href + " #timexx>*", "")
}, 3000);
});
I would recommend using an ajax data source along with ajax.reload(). In fact, the docs page I linked there has an example of just what you are after.
For your markup you can simply create the table and header:
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
</table>
Then initialize datatables with ajax data source, declare your columns and start the loop:
$(document).ready( function () {
var table = $('#example1').DataTable({
"ajax" : 'http://example.com/table_data.php',
"columns" : [
{ "data" : "id" },
{ "data" : "name" )
]
});
setInterval(function () {
// the second argument here will prevent the pagination
// from reseting when the table is reloaded
table.ajax.reload( null, false );
}, 3000);
});
Now you need a web page at the endpoint declared for your ajax data source http://example.com/table_data.php that spits out the table data as a json. There are a few ways this can be structured, but my preference is to use the data property as the docs state:
the data parameter format shown here can be used with a simplified DataTables initialisation as data is the default property that DataTables looks for in the source data object.
With this objective, your php script might look something like this:
include('../dist/includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC") or die(mysqli_error($con));
$results = [];
while ($row=mysqli_fetch_array($query)) {
$results['data'][] = [
'id' => $row['id'],
'name' => $row['name']
];
}
echo json_encode($results);
Side note, mysqli_error() expects a single argument which should be your connection resource.
Related
I am trying to display database records to my console in json format but i can't see why my request in json format is not being displayed on my console. There is no error also to guide me where i made a mistake. can someone help me. I use the MVC framework for writing my code. I want to retrieve horse names based on race number from the race table in the database.
here is my home.php
<div class="box-body">
Start creating your amazing application!
<table class="table table-bordered table-striped dt-responsive tables" width="100%">
<thead>
<tr>
<th style="width:10px">#</th>
<th>id</th>
<th>Race Number</th>
<th>Horse Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$users = ControllerUsers::ShowallUsersCtr();
foreach ($users as $key => $value) {
echo '
<tr>
<td>'.($key+1).'</td>
<td>'.$value["id"].'</td>
<td>'.$value["racenumber"].'</td>
<td>'.$value["horsename"].'</td>';
echo '<td>
<div class="btn-group">
<button class= "btn btn-primary btnAddRace" RaceNumber="'.$value["racenumber"].'" data-toggle="modal" data-target="#editUser">Add Horse - Race 1</button>
</div>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
here is my javascript file code named users.js
$(document).on("click", ".btnAddRace", function(){
var RaceNumber = $(this).attr("RaceNumber"); // capture the race number from database to the console
console.log("RaceNumber",RaceNumber);
var data = new FormData();
data.append("RaceNumber",RaceNumber);
$.ajax({
url: "ajax/users.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(answer){
console.log("answer", answer); // bring from the database whatever we asked for
}
});
});
And here is my Ajax file users.ajax.php
<?php
require_once "../controllers/users.controller.php";
require_once "../models/users.model.php";
class AjaxUsers{
public $RaceNumber;
public function ajaxEditUser(){
$item = "racenumber";
$value = $this->RaceNumber; // value what is selected from the table
$answer = ControllerUsers::ctrShowUsers($item, $value); // ask for the controller to show me the race table
echo json_encode($answer);
}
}
if (isset($_POST["RaceNumber"])) { // if the variable race number comes with information, we can execute all of this
$edit = new AjaxUsers();
$edit -> RaceNumber = $_POST["RaceNumber"];
$edit -> ajaxEditUser();
}
here is my user controller and model methods
static public function ctrShowUsers($item, $value){
$table = "race";
$answer = UsersModel::MdlShowUsers($table, $item, $value);
return $answer;
}
static public function MdlShowUsers($table, $item, $value){
$stmt = Connection::connect()->prepare("SELECT * FROM $table WHERE $item = :$item");
$stmt -> bindParam(":".$item, $value, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetch();
$stmt -> close();
$stmt = null;
}
Database Picture is here
enter image description here
After some hours dealing with it, i'll be specific.
I'm trying to pass data from a table on angular (view), to the controller, the controller call to a factory and it last make an http request to a .php file.
It isn't so hard as it seems.
This is the error i'm getting
}
Trying to get property of non-object on line 6
It's my .php file (to get a simple select query)
// Including database connections
require_once '../../db/database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * from repartidor WHERE id_repartidor = '$data->codigo'"; //THIS is **line 6**
$result = mysqli_query($con, $query);
$arr = array();
$row = mysqli_fetch_assoc($result);
$arr[0] = $row;
// Return json array containing data from the databasecon
echo $json_info = json_encode($arr[0]);
?>
However, after debugging it for a while, the query and the response of the .php file does work (i prove it replacing the '$data->codigo' with the value).
I think the problem is that the data is not reaching or is incorrectly being decoded.
Factory code:
obtenerItem: function(item){
return $http.post("http://localhost/sgzena/php/repartidor/repDetail.php", item);
} //THERE is an update
Controller code:
$scope.actualizarItem = function (item) {
repartidorFactory.obtenerItem(item) //aca iba ID
.then(function (response) {
var modal = abrirModal(response.data);
modal.result.then(function(result) {
guardarRepartidor(result);
});
});
}
View code:
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Cod.</th>
<th>Nombre</th>
<th>Telefono</th>
<th>
<em class="glyphicon glyphicon-cog" tooltip-placement="top" uib-tooltip="Acciones"></em>
</th>
</tr>
</thead>
<tbody ng-repeat="item in repartidores">
<tr class="odd gradeX">
<td>{{item.id_repartidor}}</td>
<td>{{item.nombre}}</td>
<td>{{item.telefono}}</td>
<td>
<a class="btn btn-default glyphicon glyphicon-edit " tooltip-placement="bottom" uib-tooltip="Editar Repartidor" data-toggle="modal" ng-click="actualizarItem(item)"></a>
<a class="btn btn-default glyphicon glyphicon-trash " tooltip-placement="bottom" uib-tooltip="Eliminar Repartidor" ng-click="eliminarItem(item)"></a>
</td>
</tr>
</tbody>
</table>
These are the lines which i modified and the code started to work:
old:
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * from repartidor WHERE id_repartidor= '$data->codigo'";
Solved:
$data = json_decode(file_get_contents("php://input"));
$id_repartidor = mysqli_real_escape_string($con, $data->id_repartidor);
$query = "SELECT * from repartidor WHERE id_repartidor= '$id_repartidor'";
I do not understand what I am doing wrong. Is this not the right format for performing an ajax call and returning JSON?
I am trying to return JSON to populate a DataTable. I have done something very similar to this before, but I am unable to make it work this time.
Here is the script ("api/exceptions_all.php") where I am using SQLSRV to return the JSON:
<?php
include("../include/database.php");
$select = "SELECT
''
,[FOR_PARTNER]
,[FOR_NAME]
,[SHP_PARTNER]
,[SHP_NAME]
,[MODDATE]
,[MODUSER]
,[ID]
FROM [main].[dbo].[for_exceptions]";
$query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
$out = array();
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode( $out );
sqlsrv_free_stmt($query);
?>
Now here is my javascript file ("exceptions.js") where I am trying to retrieve the JSON and print it in the datatable:
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"type": 'POST',
"ajax": 'api/exceptions_all.php',
"data": data,
"dataType": 'json',
"bDestroy": true
});
});
I keep getting an error stating "Uncaught ReferenceError: data is not defined" referring to "data": data above.
In my HTML file, I have the table where the DataTable should be populated:
<table id="example1">
<thead>
<tr>
<th>Edit</th>
<th>FF Partner Code</th>
<th>FF Name</th>
<th>SHP Partner Code</th>
<th>SHP Name</th>
<th>Modified Date</th>
<th>Modified User</th>
<th>ID</th>
</tr>
</thead>
// datatable should be here
</table>
i thing you are missing to declare the $out[] array out of while loop ;
<?php
include("../include/database.php");
$select = "SELECT
''
,[FOR_PARTNER]
,[FOR_NAME]
,[SHP_PARTNER]
,[SHP_NAME]
,[MODDATE]
,[MODUSER]
,[ID]
FROM [main].[dbo].[for_exceptions]";
$query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
$out=array();**// add this line**
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode( $out );
sqlsrv_free_stmt($query);
?>
Looks like you're using the DataTables plugin for jQuery...
Something like this maybe...
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/exceptions_all.php'
});
});
This is directly from the Docs...
I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.
In my case, I make auto refresh after X seconds. But I want to make it only refresh when new data inserted or updated.
Here is my script.
refresh.php
<script src="jquery-1.4.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("refreshnow.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('refreshnow.php?randval='+ Math.random());
}, 1000);
});
</script>
<div id="responsecontainer"></div>
refreshnow.php
<?php
$query = mysqli_query($connection,"select * from `table`");
$rows = mysqli_num_rows($query);
?>
<table style="background:#F0F0F0;" border=1 style="border-collapse:collapse">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
<tbody>
<?php
while($result = mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>".$result["name"]."</td>";
echo "<td>".$result["job"]."</td>";
echo "</tr>";
}
?>
</tbody>
So, could it be possible to load new data automatically when new data inserted or updated without refresh after x seconds?
If you want to use your existing code, just add another column in a mysql table (if you got a config or settings table, this would be easyer, if not just ad timestamp for each record you insert) with the value time(), this updates the timestamp in the database each time a row is inserted/modified.
Then just do a query like:
"select timestamp_column from `settings_table` order by timestamp_column limimt 1"
If ($result["timestamp_column"]+1000>=time()){
//do the refreshnow.php code here
}
Hope it helps,
Cheers