Passing data from PHP array to Highcharts chart with JSON - javascript

I am trying to draw a highcharts chart that comes from my sql database which i am querying with getdata.php?id=allTemp. I don't really know about JSON that much but I have assembled the code below so far, and the chart does not even draw. the $.getJSON function works when I get a single variable such as weather.wesleyweisenberger.com/getdata.php?id=humidity, but as soon as I try to fetch getdata.php?id=allTemp it does not work, please help me...
while($data = $result->fetch_assoc()){
echo json_encode($data, JSON_FORCE_OBJECT);
}
and the return is in the format
{"timestamp":"2018-05-30 00:33:05","temperature":"67.39","humidity":"66.57","pressure":"99.21"}{"timestamp":"2018-05-30 00:47:39","temperature":"65.52","humidity":"70.41","pressure":"99.2"}{...
My index.php file reads:
<script>
$(function(){
$.getJSON('getdata.php?id=allTemp', function(json){
$('#container').highcharts({
series: [{
data: json
}],
title: {
text: 'Title'
}
})
})
})
</script>
<div id="container" style="width:100%; height:400px;"></div>

{...}{...}{...}
That is an invalid json pattern. You are getting this because you are echoing multiple json objects, where the responses expects a single one. You can correct this by only echoing once.
$results = array();
while($data = $result->fetch_assoc()){
array_push($results, $data);
}
echo json_encode($results);

The Highchart uses arrays to fill its data, and you are just returning a lot of objects side by side, with no actual acceptable format, now with the code bellow, you will print an array of objects stringified.
Try this on your PHP:
var $stringToReturn = [];
while($data = $result->fetch_assoc()){
push($stringToReturn, $data);
}
echo json_encode($stringToReturn);

Related

Return data from PHP to JavaScript using AJAX - data type error?

I am using AJAX to return a query to my JavaScript function, but I am having an issue returning the json_encode. I might have an error in the data type somewhere, but thought to check here for some advice.
This is my AJAX request:
$.ajax({
url: 'testajax.php',
method: 'POST',
data: {value},
dataType:'json',
success: function(data){
console.log(data);}
});
This is my PHP script:
<?php
require 'login.php';
$connection = new mysqli($host, $user, $pword, $database, 3306);
$insertquery = $connection->prepare("SELECT tracking_type, tracking_change_date, vessel_fcm_new, vessel_hull_id_new, vessel_name_new, vessel_length_new, vessel_manufacturer_new, vessel_manufacturer_id_new, vessel_year_new, vessel_value_new, owner_id_new, loss_payee_id_new, policy_id_new, policy_start_date_new, policy_end_date_new FROM tracking WHERE tracking_type = ?");
$insertquery->bind_param("i", $trackingtype);
//$trackingtype = $_POST['value'];
$trackingtype = 1;
$insertquery->execute();
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
echo json_encode($data);
}
If I only have 1 row matching this query, then it works fine. But as soon as I add another row that matches the select query, it does not return properly to the JavaScript function, but does display fine in the browser (if you visit testajax.php).
This is currently how the data is being returned. Maybe I have an error in the data type being usesd:
["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]
This bit might have given you a clue If I only have 1 row matching this query, then it works fine
So save your rows in an array and then send the whole array like this
while ($insertquery->fetch()){
$data[] = array($tracking_type, $tracking_change_date, $vessel_fcm_new,
$vessel_hull_id_new, $vessel_name_new, $vessel_length_new,
$vessel_manufacturer_new, $vessel_manufacturer_id_new,
$vessel_year_new, $vessel_value_new, $owner_id_new,
$loss_payee_id_new, $policy_id_new, $policy_start_date_new,
$policy_end_date_new);
}
echo json_encode($data);
EDIT:
A simple test of this code would be
$data[] = array('Insert','2018-05-26', 1);
$data[] = array('Insert','2018-05-26', 2);
echo json_encode($data);
This will generate
[
["Insert","2018-05-26",1],
["Insert","2018-05-26",2]
]
and not the sample output you suggest.
The problem is that you're printing an array of columns for each pass through the loop and therefore the JSON is not be correctly encoded as an array of arrays; you can modify your code as follows:
$results = array();
while ($insertquery->fetch()) {
$newResult = array($tracking_type, $tracking_change_date, ...);
array_push($results, $newResult);
}
$encoded = json_encode($results);
echo $encoded;
Will print something like this:
[
["Insert","2018-05-26","JBL5693", ...],
["Insert","2018-05-27","JBL5694", ...],
...
]
Note that it's better to design a client<>server interface to use an array of objects, something like:
[
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
...
]
This approach has the advantage that the client client does not need to know the order of the columns, rather it can directly access the properties it cares about.
What you should be doing is return an array of objects. Not multiple objects.
$to_return = [];
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
$to_return[] = $data;
}
echo json_encode($to_return);
Make sure to keep
echo json_encode($data);
outside of the while loop.

How to insert a PHP 'while loop' into JavaScript code?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>

php/mysql write array to json file

I have the following issue, my php code gets the required data from the dB:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
As you see this writes to a json file - results:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
When I use the following js code to extract from json file:
$.getJSON('newport.json', function(data) {
console.log(data);
The console log using chrome displays the following:
[Object]
0: Object
nmech: "3.00"
__proto__: Object
length: 1
only shows the first key/value pair and not all 4 K/V pair? Can someone explain what I am doing wrong please.
Writing the results to a json file is overkill, IMHO. Why not just add the json into a Template or Page view (PHP).
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? #json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
Obviously, you don't have a Registration namespace object, but this just an example approach to setting settings from PHP when the page first loads.
All you really need it to output some data.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : json_encode(array()); ?>;
</script>
Or maybe a more simple way to write it would be.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : '[]'; ?>;
</script>
I can see your trying to file (or cache) the results. You should probably just write an AJAX method in your PHP controller to handle the request. The data could be cached server side in Memcached or some other fast handler of data. Most PHP frameworks support memcached.
This is ok, because your PHP array looks like this:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
You must use data[0]['key'] to access key1 part of first element.
Another (better solution) is to not to use while loop in php, since you are expecting 1 element in your case to be returned from mysql. Use like this then:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
Now your data will be in javascript like you expected on beginning.

How do I display this array correctly in html?

I'm sending array from Php to Javascript, then I try to generate a div for each value of that array to display them in html, but instead of making a div for each independent value it stacks them all on a single one. It seems the array I'm making in php arranges all the values from my database into single string.
How can I separate them?
Here's how the error looks upfront
Here's part of my code:
Php:
$query= "SELECT titulo FROM notas WHERE usuario_idusuario = '".$ide."'";
//Runs the search
$resultado = $conn->query($query);
if($resultado->num_rows>0){
while($row = $resultado->fetch_assoc()){
//inserts result in an array
$contenido= array('titulo'=> $row['titulo']);
//json_encode
$objJson = json_encode($contenido["titulo"]);
//sends the array to javascript
echo "$objJson\n";
}
}else{
echo "Error";
}
$conn->close();
?>
javascript:
//response receives the array
success: function(response){
console.log(response);
console.log(response.length);
var contenidoInt = new Array();
contenidoInt = [{
"titulo":response
}];
console.log(contenidoInt);
console.log(contenidoInt[0].titulo);
}
I hope someone can help me, thanks.

Returns Mysql SQL results in JSON format

I am trying to implement Typeahead.js to my site.
The typeahead.js will take from a remote page that would return JSON,
something like: http://example.org/search?q=%QUERY
For my site, this is what I've wrote for the PHP:
$q=mysql_real_escape_string($_GET['q']);
$getship= #mysql_query('SELECT * FROM `tbl` WHERE data1 LIKE \'%'.$q.'%\' OR schar LIKE \'%'.$q.'%\';');
while($tbl=mysql_fetch_array($getship)){
$id=$tbl['id'];
$data1=$tbl['data1'];
$fplod=explode(" ",$data1);
$data2=$tbl['data2'];
$splod=explode(" ",$data2);
$data3=$tbl['data3'];
$data4=$tbl['data4'];
echo '{
"value":'.$id.',
"tokens":["'.$fplod[0].'","'.$fplod[1].'","'.$splod[0].'","'.$splod[1].'"],
"data1" :"'.$data1.'",
"data2":"'.$data2.'",
"data3":"'.$data3.'",
"data4":"'.$data4.'"
}';
}
But when ever I ask that typeahead thing to return, it seems to return in text/html and not application/json .
How can I make this to work?
Thanks in advance
You can set the Content-Type header yourself. Before any output is sent, call header:
header('Content-Type: application/json');
That is not valid JSON. You do not have quotes around the names. PHP has built in json encoding/decoding functions already so you don't have to build the string yourself.
echo json_encode(array("value" => $id /* etc
It is not a good practice to convert your data into json manually, rather use json_encode
$data = array();
while($tbl=mysql_fetch_array($getship)){
$data[] = $tbl;
}
$return = array("data"=>$data);
echo json_encode($return);
try something like:
while($row = mysql_fetch_array($getship, MYSQL_ASSOC))
{
$row_set[] = $row;
}
echo json_encode($row_set);
you can also use mysql_fetch_assoc.

Categories

Resources