I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.
I am working on Highcharts using PHP/MYSQL. Data is showing properly in each chart but I tried to change one chart to ajax call in order to reduce page load.
I am generating multiple series data from PHP and displaying them back in the required format but data is not showing(I alerted the data it's coming).
Below is the code of ajax call:
function project_wise_lab(from_date, to_date) {
$.ajax({
type: "POST",
url: 'dashboard/project_wise_labtest',
data: {
from_dte: from_date,
to_dte: to_date
},
success: function(response) {
Highcharts.chart('subcontainer7', {
chart: {
type: 'line',
height: 230,
},
credits: {
enabled: false
},
title: {
text: null
},
xAxis: {
categories: ['Oct 2020', 'Nov 2020', 'Dec 2020', 'Jan 2021', 'Feb 2021', 'Mar 2021', 'Apr 2021', 'May 2021']
},
yAxis: {
min: 0,
title: {
// text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: ( // theme
Highcharts.defaultOptions.title.style &&
Highcharts.defaultOptions.title.style.color
) || 'gray'
}
}
},
legend: {
align: 'center',
verticalAlign: 'bottom',
backgroundColor: Highcharts.defaultOptions.legend.backgroundColor || 'white',
borderColor: '#CCC',
// borderWidth: 1,
shadow: false
},
tooltip: {
/* headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
*/
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
// enabled: true
}
}
},
colors: [
'#4a7fbb',
'#be4c48',
'#97b954',
'#7d6096'
],
series: response
});
console.log(response);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
}
I have alerted the response and the data is showing in the below format:
{ name : 'FKI',data : [10591,10576,9309,8422,9586,11171,9327,9384] },{ name : 'FKR',data : [4740,3105,2690,3598,3686,4930,3711,3859] },{ name : 'FHR',data : [17190,12757,10837,11944,14083,15748,12544,12494] },{ name : 'FUL',data : [1308,937,1002,1086,1452,1419,1248,1362] },{ name : 'FSW',data : [9535,9102,8689,8420,9941,10915,7273,6930] },{ name : 'FWP',data : [47437,42198,43012,44979,47377,55400,46520,41682] },{ name : 'FGR',data : [2112,1366,1619,1664,2387,2355,1633,1215] }
New Response after update:
[{"name":"FKI","data":{"01-OCT-20":"10591","01-NOV-20":"10576","01-DEC-20":"9309","01-JAN-21":"8422","01-FEB-21":"9586","01-MAR-21":"11171","01-APR-21":"9332","01-MAY-21":"9384"}},{"name":"FKR","data":{"01-OCT-20":"4740","01-NOV-20":"3105","01-DEC-20":"2690","01-JAN-21":"3598","01-FEB-21":"3686","01-MAR-21":"4930","01-APR-21":"3711","01-MAY-21":"3859"}},{"name":"FHR","data":{"01-OCT-20":"17190","01-NOV-20":"12757","01-DEC-20":"10837","01-JAN-21":"11944","01-FEB-21":"14083","01-MAR-21":"15748","01-APR-21":"12544","01-MAY-21":"12494"}},{"name":"FUL","data":{"01-OCT-20":"1308","01-NOV-20":"937","01-DEC-20":"1002","01-JAN-21":"1086","01-FEB-21":"1452","01-MAR-21":"1419","01-APR-21":"1248","01-MAY-21":"1362"}},{"name":"FSW","data":{"01-OCT-20":"9535","01-NOV-20":"9102","01-DEC-20":"8689","01-JAN-21":"8420","01-FEB-21":"9941","01-MAR-21":"10915","01-APR-21":"7273","01-MAY-21":"6930"}},{"name":"FHP","data":{"01-OCT-20":"47437","01-NOV-20":"42198","01-DEC-20":"43012","01-JAN-21":"44979","01-FEB-21":"47377","01-MAR-21":"55400","01-APR-21":"46520","01-MAY-21":"41682"}},{"name":"FGR","data":{"01-OCT-20":"2112","01-NOV-20":"1366","01-DEC-20":"1619","01-JAN-21":"1664","01-FEB-21":"2387","01-MAR-21":"2355","01-APR-21":"1633","01-MAY-21":"1215"}}]
The chart is showing empty, kindly help and let me know to get the issue resolve?
Thanks
You appear to have two problems...
jQuery is interpreting your response as plain text (a string) where Highcharts expects actual JS objects
Your response is not valid JSON so you can't interpret it as such on the client-side. Rule #1 when creating JSON responses is... never roll your own JSON.
I recommend getting PHP to generate valid JSON and respond with the correct Content-type
// Ensure jQuery (or any consumer) knows the response is JSON
header("Content-type: application/json");
// Create a data structure representing the series data
$data = [];
foreach ($project as $key => $value) {
$data[] = [
"name" => $key,
"data" => array_values($value) // you just want the values here, not the keys
];
}
// Respond with JSON
echo json_encode($data);
exit;
Then in your client-side code, you can simply use
series: response
as response will now be a valid JS array
You can also make sure jQuery treats the response as JSON by adding
dataType: "json",
to your $.ajax() options but with the right Content-type response header, jQuery should not need this.
Just an FYI, alert() is terrible for viewing data. The best option would be to use your browser's debugger. The second best option is to use console.log()
I'm trying to use Data-tables but I need to pass a value from Ajax to PHP file.
the Ajax part is like this:
<script>
$(document).ready(function() {
var oTable =
$('#user-list').DataTable({
"serverSide": true,
"ajax": {
"url": "assets/server_processing_reminders.php",
"data": {
"CurrentFlag": 1
}
},
"columnDefs": [{
"width": "6%",
"targets": 0
}],
"order": [
[1, "asc"]
]
});
});
</script>
on the server side Im trying to get the variable "CurrentFlag" using:
<?php
if (isset($_GET["CurrentFlag"])){
$cf = $_GET["CurrentFlag"];
}
echo $cf;
but the php file is not printing out the value send.
Thanks for any help
Please use $_REQUEST instead of $_GET like this :
if(isset($_REQUEST["CurrentFlag"]))
{
$cf = $_REQUEST["CurrentFlag"];
}
echo $cf;
OR
If you want print data using $_GET method please add type:GET under ajax call
You need to provide request type as GET as shown here.
"ajax" : {
"url": "assets/server_processing_reminders.php",
type: "GET",
"data": {
"CurrentFlag": 1
}
}
Use Jquery for better code and results.
Learn Ajax using this link :
https://www.w3schools.com/js/js_ajax_intro.asp
I've such a simple question but can't find answer (documentation) on it. I've created Grid , where information is retrieved from MySQL database. Using Ext JS 4.2 .
Let's take a look of script ...
Ext.define("AppStore",{
extend: "Ext.data.Model",
fields: [
{name: "nickname" , type: "auto"},
{name: "email" , type: "auto"}
]
});
var store = Ext.create("Ext.data.Store",{
model: "AppStore",
proxy: {
type: "ajax",
api: {
read : "./read.php",
update : "./update.php"
},
reader: {
type: "json",
root: ""
},
writer: {
type: "json",
writeAllFields: true,
encode: false,
root: ""
}
},
listeners: {
read: function(operation, callback, scope){
},
update: function(operation, callback, scope){
// Do I have to do something from here ?
}
},
autoLoad: true
});
Ext.create("Ext.grid.Panel",{
store: store,
selMode: "cellmodel",
columns: [
{
text: "Nickname",
flex: 1,
dataIndex: "nickname",
editor: {
xtype: "textfield",
allowBlank: false
}
},
{
text: "Email",
flex: 1.5,
dataIndex: "email",
editor: {
xtype: "textfield",
allowBlank: false
}
}
],
plugins: [
Ext.create("Ext.grid.plugin.CellEditing",{
clicksToEdit: 2
})
]
});
Everything is working fine , just interested in how I have to send request to MySQL for updating data after changing it in Grid cell . Any example , documentation or the way how to accomplish this task will be appreciated , thanks ...
Typically, you'll want to call sync() on your grid's store in order to persist the model changes to the server. This can be configured to occur automatically on every edit (see the autoSync property of the store). However, I would suggest it's better to handle the sync() call based on some specific action (e.g., a "Save" button being clicked, etc.).
I want to retrieve values dynamically from the database and plot using Highcharts spline graph. The problem is I cant figure out a way to pass the values to Javascript function without refreshing the whole function, this will plot the whole graph from the scratch. The current code contains an array where it just plots using an array and a random function to generate new values. I want to find a way to insert new values on to that array from the database using PHP. Problem is I don't know how to keep on calling the database query without affecting the graph. Some help on plotting the graph dynamically using the dynamic values from the database would be helpful.
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Trend analysis'
},
xAxis: {
labels: {
rotation: 320
},
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits:{
enabled:false
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
The technique you are looking for is called ajax. This is where the javascript requests more data from the server without the whole page loading. The basic approach is:
The page is loaded and renders the initial chart.
The page then requests additional data fromthe user. In jquery, this is done using a call to$.ajax
The server responds with some more data.
The javascript loads this data into the chart using chart.series.addpoint or chart.series.setData.
Steps 2 to 5 are then repeated at regular intervals.
Highcharts has good article on this here: http://docs.highcharts.com/#preprocessing-live-data with some example code. You will need to amend the php to read the data from your database, and you may want to change the shift logic in the javascript depending on whether you want old points to drop off, or stay on the chart.
If you series isn't too big, it's not unreasonable to return the whole data set each time and use chart.series.setData to replace the entire series, instead of doing it point by point. The API calls you need are documented here: http://api.highcharts.com/highcharts#Series