I'm fresh, but I'm learning with the help of people like you :). I need to do a table on my site that will display sorted data by type and pagination. I thought to use this solution: https://legacy.datatables.net/examples/data_sources/server_side.html
But honestly, I do not know how to do this. Can someone give an example along with html how to do it? Or suggest a different solution?
First of you need to import some of the necessary files:
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
CSS :
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
Then using the id attribute of the table you have created use the following code :
var table = $('#myTable').DataTable(); // this creates a table object of the DataTable class
// myTable is the id of the table you have created
table.clear().draw();
table.destroy();
$.ajax({
url: 'abc.php',
type: 'POST',
data: {value:value},//value you want to send to backend
dataType: 'json',
success:function(result){
$('#myTable').DataTable( {
"pageLength": 10, // does pagination providing 10 records per page
"destroy": true,
"language": {
"zeroRecords": "No Data Found",
"infoEmpty": "No Data Found",
},
"ajax": "objects.txt",
// Data from backend is sent to objects.txt file in JSON format
"columns": [
{ "data": "Key value from backend for 1st column in table" },
{ "data": "Key value from backend for 2nd column in table" },
{ "data": "Key value from backend for 3rd column in table" },
{ "data": "Key value from backend for 4th column in table"},
{ "data": "Key value from backend for 5th column in table" },
{ "data": "Key value from backend for 6th column in table" }
]
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
You could import more datatable javascripts that can provide more functionality such as conversion of table data to pdf or export as an excel file using button datatable javascripts. You can find more related information here : https://cdn.datatables.net/
Related
I am using Spatie for logging activities in my web site. I created a table where the data from activity_log database table will be displayed. There's no problem in retrieving the data from database but my problem is that whenever I display the values from properties column it only displays [object Object].
Here's what the data table looks like:
While it's actual values in the database table of activity_log is this:
Here's my snippet code from my controller:
public function datatable_Activities()
{
$data = Activity::all()->where('causer_id', '=', Auth::user()->id);
return Datatables::of($data)->make(true);
}
Snippet code for displaying the data in my blade file:
<script>
$(function () {
$("#activity_table_log").DataTable({
responsive:true,
processing:true,
pagingType: 'full_numbers',
stateSave:false,
scrollY:true,
scrollX:true,
ajax:"{{route('datatable_Activities')}}",
order:[0, 'desc'],
columns:[
{data:'log_name', name: 'log_name'},
{data:'description', name: 'description'},
{data:'subject_id', name: 'subject_id'},
{data:'properties', name: 'properties'},
{data:'created_at', name: 'created_at', searchable: false, sortable:false},
]
});
});
</script>
I already tried json_decode() but unfortunately it is not working..
How to display it properly like the values stored in properties
column in database not the [object Object]?
However when I check the response in Developer's Tool it retrieves the values of properties exactly from the database.
Here's the example nested JSON object I am trying to put in the data table:
{
"id":6,
"log_name":"PurchaseH",
"description":"A purchase h has been updated",
"subject_id":1,
"subject_type":"App\\Model\\Purchase\\PurchaseH",
"causer_id":1,
"causer_type":"App\\User",
"properties":{
"attributes":{
"total":1250000
},
"old":{
"total":null
}
},
"created_at":"2020-06-14T09:04:34.000000Z",
"updated_at":"2020-06-14T09:04:34.000000Z"
},
P.S. I'm Using latest Google chrome, Laravel Framework and Spatie.
I have a code below and I have tried it already and its working.
What I am trying to achieve is to load data using ajax to my data tables.
The code below is working but now I would to refresh every 5 to 10 second checking if there is new data in the database.
$(document).ready(function () {
$("#get_categories").DataTable({
"ajax": { //create an ajax request to display.php
"url": "process/get_categories.php",
"dataSrc": ""
},
"columns": [
{"data": "id"},
{"data": "name"},
{"data": "action"}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
As you've already defined an AJAX source for your DataTable you can simply call reload() in an interval:
var table = $("#get_categories").DataTable({
// settings...
});
setInterval(function () {
table.ajax.reload();
}, 10000);
However, as #ADyson mentions in the comments, refreshing a data source this often can lead to server load problems, depending on how may concurrent users you have accessing the data. I'd suggest looking in to using WebSockets or Server Sent Events as a more scalable alternative.
I'm trying to make a simple ajax call in datatables that is reliant on a post array of IDs from a previous page's form. I am getting the error :
Invalid JSON Response
which tells me that my returned json array is probably empty or something and I have a feeling it has to do with the POST data not being sent to my php/sql external script on which ajax is requesting the data from.
I'm not sure how to test it as I don't know how to include the $_POST data in the URL to my external php page to outright trigger the script.
Heres my current datatables init and php from the results page:
<?php
include_once('../functions.php');
sec_session_start();
print_r($_POST['post_id']); <-- making sure the post data made it this far
?>
<script type="text/javascript">
$(document).ready(function() {
var compTable = $('#compTab').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "baddebt_ext_sql.php",
"type": "POST",
"dataType": 'json',
"data": {"post_id": $_POST['post_id']}
},
"Columns": [
{ "data": "provider_num" },
{ "data": "provider_name"},
{ "data": "261_total_bed_debts", "sClass": "rightAlign" },
{ "data": "271_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "281_non_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "1_cost_to_charge_ratio", "sClass": "rightAlign" },
{ "data": "291_cost_of_non_mcr_bad_debts", "sClass": "rightAlign" }
],
"scrollY": "600px",
"scrollCollapse": true,
"paging": false,
"order": [[ 2, "desc" ]],
"oLanguage": { "sSearch": "Filter All Fields By:" },
"Dom": '<"clear">lfrtipT',
"TableTools": {
"sSwfPath" : "../php/tabletools/swf/copy_csv_xls_pdf.swf" }
});
and here is my SQL:
<?php
include_once('../link_costreport_2013.php');
if(isset($_POST['post_id'])){
$in = $_POST['post_id']; <-- THIS IS WHERE THE POST DATA IS SUPPOSED TO BE RECEIVED
}
$data = array();
foreach ($in as $id){
$query = $link->prepare("SELECT id,provider_num, provider_name, 261_total_bed_debts, 271_medicare_bad_debts, 281_non_medicare_bad_debts, 1_cost_to_charge_ratio, 291_cost_of_non_mcr_bad_debts
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
$results['261_total_bed_debts'] = "\$".number_format($results['261_total_bed_debts']);
$results['271_medicare_bad_debts'] = "\$".number_format($results['271_medicare_bad_debts']);
$results['281_non_medicare_bad_debts'] = "\$".number_format($results['281_non_medicare_bad_debts']);
$results['291_cost_of_non_mcr_bad_debts'] = "\$".number_format($results['291_cost_of_non_mcr_bad_debts']);
$results['provider_name'] = "<a id='".$results['id']."' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
$data[] = $results;
}
echo json_encode($data);
If anyone knows how I can get my json array from this script without utilizing the previous pages $_POST data it is supposed to send, then I will gladly post it as well.
Basically I'm just wondering if there are any steps I am missing when it comes to feeding this array of IDs through my datatables ajax query and into the second page's sql. ( an example of the post_id array is like this:
Array ( [0] => 299 [1] => 1555 [2] => 3539 ))
Diagnosing this problem is pretty easy. Simply right mouse click and "inspect element" then choose the Network tab. Toggle the transaction as you would in your interface. You'll see a new network transaction in the network tab.
Click on that new network transaction -- it should have the address that you're defining in the ajax call. The headers will show the variables you sent via post, response will show what the server returned.
The error is indicating that your response will fail if you paste the payload into jslint.com and evaluate it. What the cause of that failure is will require more details than you've provided.
In the ajax example you use, "data" is the data that's being sent to the server. To send a large amount of data in that post, I'd enclose your inputs in a form tag, then do a $.serialize or $.serializeArray on that form. You can then send that serialized data over as a variable via the data attribute, where it will be posted to your server. From there, just deal with the resulting post variables via PHP.
Please do update your code to use 1.10 API variables. Support for the old ones will be deprecated in the future versions.
I have this simple code:
var store = {
"(name)": "My Object",
"Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),
"Available": false,
"Version": 0.01,
"Description": "A test object"
}
Ext.create('Ext.grid.property.Grid', {
title: 'Properties Grid',
width: 300,
renderTo: Ext.getBody(),
source: store,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
items: ['->', {
//iconCls: 'icon-save',
text: 'Sync',
scope: this,
// handler: this.onSync
}]
}]
});
The panel looks like this:
My app uses similar grid, the only difference is that the store variable is created dynamically (but has similar structure) and I also have a sync button that should save any changes to the grid's value field.
As of now, value field can be edited but not saved anywhere of course. I have been trying to add an event on sync button click, that would get all the rows from value and update the database.
Can anyone tell me step-by-step what to add in property.Grid's code, so that when I click sync
it would send all the values via AJAX to my php file, that would do the sync with database?
Thanks
Something like this should do the trick:
{
text: 'Sync',
handler: function() {
// get values
var gridvalues = this.up( 'propertygrid' ).getSource();
// send AJAX request
Ext.Ajax.request({
url: 'somephpurl...',
params: gridvalues
});
}
}
The docs, BTW, for these are as follows:
Get property grid values: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.grid.property.Grid-method-getSource
Create AJAX request: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Ajax-method-request
Hello StackOverFlow nation . I'm trying to add information to jqGrid , which is retrieved from MySQL database. I've two files => index.html and data.php (both in the same directory)
index.html source =>
<script type="text/javascript">
$(function(){
$("#jqGrid_tb").jqGrid({
url: "data.php",
datatype: "json",
sortable: true,
height: "auto",
colNames: ["Name","Surname","Birth Year","Famous Film"],
colModel: [
{name: "name", index: "name", width: "150"},
{name: "surname", index: "surname", width: "150"},
{name: "b_year", index: "year", width: "150"},
{name: "film", index: "film", width: "200"}
],
rowNum: 5,
rowList: [5,10,15],
viewrecords: true,
pager: $("#pager"),
caption: "Famous Actors",
}).navGrid("#pager");
});
</script>
<div id="grid">
<table id="jqGrid_tb"></table>
<div id="pager"></div>
</div>
data.php source =>
include ("JSON.php");
$json = new Services_JSON();
$con = new mysqli("host","user","pswd","db");
if (!$con->connect_errno){
if ($r = $con->query("SELECT * FROM actors")){
while ($row = $r->fetch_assoc()){
$info[] = array(
"name" => $row[name],
"surname" => $row[surname],
"b_year" => $row[b_year],
"film" => $row[film],
);
}
$r->free();
}
}
echo $json->encode($info);
if (isset($con)){
$con->close();
}
jqGrid is shown without any information in index.html file , also when opening data.php file information is successfully encoded into JSON format , whats wrong I can't understand . Please help , thanks ...
Your response format is wrong. You can go to jqGrid Demos page where you will find a sample for PHP/MySQL after expanding Loading Data and then choosing JSON Data.
The proper format of data should look like this:
{
"total": "1",
"page": "1",
"records": "2",
"rows": [
{ "name": "Robert", "surname": "De Niro", "b_year": "1943", "film": "Once Upon A Time In America" },
{ "name": "Al", "surname": "Pacino", "b_year":"1971", "film": "Scent Of A Woman"}
]
}
Where:
total --> total count of pages
page --> current page number
records --> total count of records
rows --> the rows of data
Also if you want rows to be objects, you need to disable repeatitems in jqGrid jsonReader options:
$("#jqGrid_tb").jqGrid({
...
jsonReader: { repeatitems: false }
});
It is also adviced for rows to have unique id for later reference.
You should include
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
as additional option of jqGrid is you don't want to change format of input data. Moreover you should specify which values should assign jqGrid as id attribute of the row. You can include additional id property as additional property of every returned item or you can add key: true property to the column (in colModel) which contains unique values. For example if you can guarantied that the values from "name" are already unique then you can include key: true property in definition of "name" column.
Additionally you can consider to use loadonce: true option of jqGrid. In the case the full data of the grid will be loaded at once and the sorting, paging and searching (filtering) of data will be implemented by jqGrid on the client side without needs to implement some additional code on the server side. You should don't use the option in case of large number of rows (many hundred or many thousand rows) in the grid.