Get json data from php using javascript - javascript

I am new to json .I am getting the data from php code in json format..
[
{
"Title": "New Event",
"TYPE": "info",
"StartsAt": "16 November 201512:00",
"EndsAt": "25 November 201512:00"
},
{
"Title": "Party",
"TYPE": "warning",
"StartsAt": "25 November 2015 09:30",
"EndsAt": "25 November 2015 5:30"
},
]
I have a javascript file demo.js
I want to receive this data in js file, currently the data is hardcoded. I want to show the events which I fetch from db.
vm.calendarView = 'month';
vm.calendarDay = new Date();
vm.events = [
{
title: 'An event',
type: 'warning',
//startsAt: moment().startOf('week').subtract(2, 'days').add(8, 'hours').toDate(),
//endsAt: moment().startOf('week').add(1, 'week').add(9, 'hours').toDate(),
startsAt:new Date(2015,10,1,1),
endsAt:new Date(2013,5,1,1),
draggable: true,
resizable: true
}, {
title: '<i class="glyphicon glyphicon-asterisk"></i> <span class="text-primary">Another event</span>, with a <i>html</i> title',
type: 'info',
startsAt: moment().subtract(1, 'day').toDate(),
endsAt: moment().add(5, 'days').toDate(),
draggable: true,
resizable: true
}, {
title: 'This is a really long event title that occurs on every year',
type: 'important',
startsAt: moment().startOf('day').add(7, 'hours').toDate(),
endsAt: moment().startOf('day').add(19, 'hours').toDate(),
recursOn: 'year',
draggable: true,
resizable: true
}
];

If the question is roughly "How do I get data from my database and output it as JSON in Javascript" then hopefully the following pseudo code will guide you in the right general direction.
<?php
include 'db.php';
$json=array();
/* Query the db */
$sql='select * from `events`;';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
$json[]=array(
'title' => $rs->title,
'type' => $rs->type,
'startsAt' => $rs->startsAt,
'endsAt' => $rs->endsAt,
'draggable' => $rs->draggable,
'resizable' => $rs->resizable
);
}
}
$db->close();
$js_json_var=json_encode( $json, JSON_FORCE_OBJECT );
?>
<html>
<head>
<title></title>
<script>
var json=<?php echo $js_json_var;?>;
/* Other js code */
</script>
</head>
<body>
<h1>json</h1>
</body>
</html>

Javascript: AJAX request:
var events;
$.ajax({
url: '/data.php',
success: function(data){
events = JSON.parse(data);
}
});
data.php is like this
$db = new PDO(/* init connection here */);
print json_encode($db->query('select * from `tablename`')->fetchAll(PDO::FETCH_ASSOC));

// In javascript
$.ajax({
type: 'post',
url: 'data.php',
data: 'data',
cache: false,
success: function(data)
{
console.log(data);
}
});
// In data.php
header('Content-type: application/json');
$data = array();
$sql = "SELECT * FROM TABLE_NAME";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
echo json_encode($data, true);

Related

How do i get updated values from php JSON in canvasJS?

Im stuck at trying to get updated values from the JSON array and plotting it on canvasJS.
Here is my JSON array for sensor 1:
[{
"Date": "2020-01-24 07:35:46",
"sensorValue": 213
}, {
"Date": "2020-01-24 07:35:46",
"sensorValue": 433
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 321
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 43
}, {
"Date": "2020-02-12 03:30:57",
"sensorValue": 4321
}]
Below is my index2.php file
the updateChart function doesn't seem to work. Im not sure if this is the right way to do it.
the rationale behind the code: I wish to update the graph every few seconds with updated values retrieved thru php. if there are no updated values, the array should not change. hence the reason behind the for-loop and the date comparison.
<?php
include 'getsensor.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
<?php
getSensor();
?>
var updateInterval = 2000;
var sensor1Data = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var sensor2Data = <?php echo json_encode($json_sensor2, JSON_NUMERIC_CHECK); ?>;
// sensor datapoints
var sensor1 = [], sensor2 = [], sensor3 = [], sensor4 = [], sensor5 = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title: {
text: "Soil Moisture Reading"
},
axisX: {
title: "chart updates every " + updateInterval / 1000 + " secs"
},
axisY:{
includeZero: false
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
verticalAlign: "top",
fontSize: 22,
fontColor: "dimGrey",
itemclick : toggleDataSeries
},
data: [{
type: "line",
name: "Sensor 1",
dataPoints: sensor1
},
{
type: "line",
name: "Sensor 2",
dataPoints: sensor2
}]
});
for(var i = 0; i < sensor1Data.length; i++) {
sensor1.push({
x: new Date(sensor1Data[i].Date),
y: Number(sensor1Data[i].sensorValue)
})
}
for(var i = 0; i < sensor2Data.length; i++) {
sensor2.push({
x: new Date(sensor2Data[i].Date),
y: Number(sensor2Data[i].sensorValue)
})
}
chart.render();
setInterval(function(){updateChart()}, updateInterval);
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
function updateChart() {
// retrieves new data from database. updates and shifts the graph.
<?php
getSensor();
?>
var sensor1DataNew = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var i = sensor1DataNew.length - 1;
// retrieve the index of the new value
for (i; i > 0; i--){
if (sensor1DataNew[i].Date == sensor1Data[19].Date){
break;
}
}
// pushes the new values to be plotted
for(i; i < sensor1DataNew.length; i++) {
sensor1.push({
x: new Date(sensor1DataNew[i].Date),
y: Number(sensor1DataNew[i].sensorValue)
})
}
if(sensor1.length > 20){
sensor1.shift();
}
chart.render();
}
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
here is my getSensor.php file:
<?php
require_once 'mysqldb.php';
$json_sensor1 = array();
$json_sensor2 = array();
$json_sensor3 = array();
function getSensor(){
global $json_sensor1, $json_sensor2, $json_sensor3;
global $db_host, $db_user, $db_pass, $db_name;
/* start connection */
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
# get/display datetime and sensor value
$sensor1 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 1" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor2 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 2" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor3 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 3" ORDER BY ID ASC, Date DESC LIMIT 20';
// $sensor3 = 'SELECT Date, sensorName, sensorValue FROM sensor WHERE Date IN (SELECT MAX(Date) FROM sensor WHERE sensorName = "sensor 3") ORDER BY ID ASC, Date DESC';
$json_sensor1 = sqlQuery($conn,$sensor1);
$json_sensor2 = sqlQuery($conn,$sensor2);
$json_sensor3 = sqlQuery($conn,$sensor3);
/* close connection */
mysqli_close($conn);
}
function sqlQuery($conn,$sql_query){
$json_array = array();
if($query = mysqli_query($conn,$sql_query)){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$json_array[] = $row;
}
/* free result set */
mysqli_free_result($query);
}
return $json_array;
}
?>
I can't comment, but I think the problem lies in the way you load the data (or the lack of it).
Basically you are loading the data on the PHP page render once, and that is all.
You need some ajax requests periodically to load the data instead of the PHP echo in the updateChart method. (In the initialization part it is fine)
$.ajax({
type: "GET",
url: 'getSensorData.php',
dataType: "text",
async: false,
success: function(data){
sensor1DataNew = data;
}
});
Something like this might work (with a little jquery)

DataTable not accepting json from database

I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format
{"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}
which according to a json validator is valid json but when I reload my page I get an error
"table id=example - Invalid JSON response".
So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is
<?php
include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
<div class="main-wrapper">
<h2>Home</h2>
<?php
if (isset($_SESSION['u_id'])) {
$sql = "SELECT * FROM employee;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
echo
"<table id='example' class='display' cellspacing='0' width='100%'>
<thead>
<tr>
<th></th>
<th>ssn</th>
<th>dob</th>
<th>first</th>
<th>MI</th>
<th>last</th>
</tr>
</thead>";
}
}
?>
</div>
</section>
<script>
console.log("In the script open");
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "infograb.php",
table: "#example",
fields: [ {
label: "Social#:",
name: "ssn"},
{
label: "DOB:",
name: "dob"},
{label: "First Name:",
name: "fn"},
{
label: "Middle Initial:",
name: "mi"},
{
label: "Last Name:",
name: "ln"
}
]
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 1 ) {
editor.bubble( this, ['fn', 'mi', 'ln'], {
title: 'Edit name:'
} );
}
else if ( index === 2 ) {
editor.bubble( this, {
buttons: false
} );
}
else if ( index === 3 ) {
editor.bubble( this );
}
} );
var testData = [{
"ssn": "98727748",
"dob": "2016-02-05",
"fn": "jake",
"mi": "a",
"ln": "butler"
}];
$('#example').DataTable( {
dom: "Bfrtip",
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
columns: [
{//sets the checkbox
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "dob" },
{ data: "ssn" },
{ data: "fn" },
{ data: "mi" },
{ data: "ln" },
],
order: [ 1, 'asc' ],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
console.log("End script");
</script>
<?php
include_once 'footer.php';
?>
and here is the php file that queries the database and returns(allegedly) the json data
<?php
include_once 'dbconn.php';
$rows = array();
$sql = "SELECT * FROM employee";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('data'=>$rows));
echo "</pre>";
?>
I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.
Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.
I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
Should go back to
ajax:{
url: 'infograb.php',
},
Remove the pre tags from infograb.php as well as they are unnecessary.
That should load the data into the table for you. You can then start working on the editing side.
Worthwhile Reading and Documentation:
Ajax sourced data
PHP libraries
DataTables Editor 1.7.3 - PHP 5.3+ libraries

Can't display highchart with my json data

I am using highchart to draw the graph, but there's a problem that I can't draw the graph when I tried to replace the URL of $.getJSON('URL', function (data)) to
$.getJSON('Highchart_getData.php', function (data) there's nothing displayed.
I choose this example
http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/demo/flags-placement/
Then I want to connect my mysql data to draw the graph.
JS.javascript:
$.getJSON('Highchart_getData.php', function (data) {
var lastDate = data[data.length - 1][0], // Get year of last data point
days = 24 * 36e5; // Milliseconds in a day
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: '光照量歷史圖表'
},
yAxis: {
title: {
text: '單位:Lux'
}
},
series: [{
name: '當日光照量',
data: data,
id: 'dataseries',
tooltip: {
valueDecimals: 4
}
}, {
type: 'flags',
name: 'Flags on series',
data: [{
x: lastDate - 60 * days,
title: 'On series'
}, {
x: lastDate - 30 * days,
title: 'On series'
}],
onSeries: 'dataseries',
shape: 'squarepin'
}, {
type: 'flags',
name: 'Flags on axis',
data: [{
x: lastDate - 45 * days,
title: 'On axis'
}, {
x: lastDate - 15 * days,
title: 'On axis'
}],
shape: 'squarepin'
}]
});
});
Highchart_getData.php:
<?php session_start(); ?>
<?php
$hostdb = "localhost";
$userdb = "root";
$passdb = "";
$namedb = "light_care";
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
include("mysql_connect.inc.php");
$id=$_SESSION['username'];
$today= date('Y')-2000;
$today .= date('-m-d');
$arrData = array();
if($_SESSION['username'] != null)
{
$sqlID = "select * from user where username='$id'";
$resultID = mysql_query($sqlID);
$userID=array();
if($resultID === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($resultID))
{
$userID[0]=$row["ID"];
}
for( $a=0;$a<30;$a++)
{
$date= date('Y')-2000;
$date .= date('-m-d',time()-24*60*60*$a);
//$date= date('Y-m-d',time()-24*60*60*$a);
$sql = "select * from data where user_id='$userID[0]' and data_time like
'%$date%'";
$result = mysql_query($sql);
$light=array();
//echo $date;
$count=0;
$light_sum=0;
$step_sum=0;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$lsum=array();
$ssum=array();
$Data=0;
while($row = mysql_fetch_array($result))
{
$Date=$row["data_time"];
$Data+=$row["light"];
//$light_sum+=$Data[$count];
//$DATE=$Data[$count];
$count++;
}
//echo $date;
$date= date('Y');
$date .= date('-m-d',time()-24*60*60*$a);
$DATA[0]=$date;
$DATA[1]=$Data;
array_push($arrData,$DATA);
$light_sum=0;
}
/*JSON Encode the data to retrieve the string containing the
JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
print($jsonEncodedData);
//Close the database connection
$dbhandle->close();
}
// }
?>
and the ouput is:
[["2017-07-20",0],["2017-07-19",0],["2017-07-18",562],["2017-07-17",746],["2017-07-16",0],["2017-07-15",0],["2017-07-14",0],["2017-07-13",0],["2017-07-12",0],["2017-07-11",0],["2017-07-10",0],["2017-07-09",0],["2017-07-08",0],["2017-07-07",0],["2017-07-06",0],["2017-07-05",0],["2017-07-04",0],["2017-07-03",0],["2017-07-02",0],["2017-07-01",0],["2017-06-30",0],["2017-06-29",0],["2017-06-28",0],["2017-06-27",0],["2017-06-26",0],["2017-06-25",0],["2017-06-24",0],["2017-06-23",0],["2017-06-22",0],["2017-06-21",0]]
JQ.html:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://code.jquery.com/jquery-
3.1.1.min.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
<script type="text/javascript" src="JS.js"></script>
</html>
but there's nothing being displayed :(
I have struggle for many days, but it still can't work...
Is there anyone can help me .
Thank you very much! and sorry for my poor English.

Popover image on hover bootstrap table

I'm completely new to web technologies,
I have a table that retrieves data from a database and they are displayed with bootstrap table.
Check out the interface image
I have usernames;
each username has their own image.
I have the images for every username stored online.
with the following naming:
username= 111
has an image with the name 111.jpg
stored on localhost/images/111.jpg
What I want to achieve is when I hover over any username in the table, their image is displayed.
list-user.php file
<?php
require 'db.php';
$sqltran = mysqli_query($con, "SELECT * FROM users ")or die(mysqli_error($con));
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'user'=> $rowList['username'],
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
?>
`
what matters from index.php file
<script type="text/javascript">
var $table = $('#table');
$table.bootstrapTable({
url: 'list-user.php',
search: true,
pagination: true,
buttonsClass: 'primary',
showFooter: true,
minimumCountColumns: 2,
columns: [{
field: 'num',
title: '#',
sortable: true,
},{
field: 'user',
title: 'Username',
sortable: true,
}, ],
});
</script>
Thats what I'm trying to accomplish something like this
What I want to accomplish (IMAGE )

How to read in data array return from ajax for google chart?

var e = $.ajax({
type: "POST",
url: "<?php echo $template->get_template_dir('ajax',DIR_WS_TEMPLATES, $current_page_base,'ajax'); ?>/survey_save.php",
data: str
}).done(function(data) {
alert("Survey has been saved."+data);
$('#form').hide();
$('#results').show();
// data array for google chart
var e = [["Element", "Density", { role: "style" } ],["Copper", 8.94, "#b87333"],["Silver", 10.49, "silver"],["Gold", 19.30, "gold"],["Platinum", 21.45, "color: #e5e4e2"]];
return e;
});
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(e);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
}
So the code above will return the data array as JSON. I need to either return it as an array or convert the JSON to an array format. How could I do that? When trying to call the
Explanation:
Pass AJAX request and get response data in JSON using mysql query. Feed response data to chart function.
In short, you need to get array values -> convert into JSON and give those values to google chart irrespective whether you need mysql or not. Modify code according to your requirement.
Client side main php
<script>
drawLineChart('<?php echo strtolower($chartType); ?>');
</script>
Client side function php
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $server_script_path; ?>",
data: { id1: chartType, id2: "Chart" },
dataType:"json",
async: false,
beforeSend: function() {
},
success: function(data) {
},
}).responseText;
var options;
options = {
title: chartTitle,
width: '390',
height: '300',
vAxis: {title: '<title>'},
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
Server side php file
if ($_GET['id1'] != "" && $_GET['id2'] == "Chart") {
// Chart type
$chartType = explode('-', $_GET['id1'])[1];
$sql = "<mysql query>";
$result = mysqli_query($conn, $sql);
$table = array();
$rows = array();
$rows[] = array('<column1>', '<column2>');
while($row = mysqli_fetch_array($result)) {
$rows[] = array('<rows>', '<rows>');
}
$table = $rows;
echo json_encode($table);
}
Live chart (my array data)

Categories