I don't think I'm understanding JSON completely, here is my code:
$.ajax({
type: "POST",
url: baseurl + "analytics/grab_points"
}).done(function(data) {
console.log(data);
var line1=$.parseJSON(data);
console.log(line1);
var plot2 = $.jqplot('chartdiv', line1, {
title: 'Customized Date Axis',
gridPadding: {right: 35},
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {formatString: '%b %#d, %y'},
min: 'May 30, 2008',
tickInterval: '1 month'
}
},
series: [{lineWidth: 4, markerOptions: {style: 'square'}}]
});
});
jqPlot seems to expect data like so:
[['2008-06-28 8:00AM', 4], ['2008-6-30 8:00AM', 1], ['2008-8-30 8:00AM', 5.7]]
(that should the content in var line1)
My server side code (PHP):
$test=array(
"2008-06-28 8:00AM" =>4,
"2008-6-30 8:00AM" =>1,
"2008-8-30 8:00AM" =>5.7,
);
echo json_encode($test);
My console logs:
{"2008-06-28 8:00AM":4,"2008-6-30 8:00AM":1,"2008-8-30 8:00AM":5.7} analytics:103
Object {2008-06-28 8:00AM: 4, 2008-6-30 8:00AM: 1, 2008-8-30 8:00AM: 5.7} analytics:105
Uncaught Error: No data specified
Pretty sure I'm going barbarian on this JSON (growing pains), any idea would be great.
if you want to get the same structure that jqPlot wants you'll have to change your array in your php code...
jqPlot is expecting something like in your php array-structure:
$test = array(
array("2008-06-28 8:00AM",4),
array("2008-6-30 8:00AM",1)
);
check example 2 on http://php.net/manual/en/function.json-encode.php (the $c)
the {} you see is just because you output it as object rather than as array, but this should be the same as the [] (this is also explained on the php manual)
EDIT: also i don't think this line: var line1=$.parseJSON(data); is still needed because your data is already json.
Related
I know you can pass arbitrary data into your time series points, such as:
new Highcharts.Chart( {
...,
series: [{
name: 'Foo',
data: [ { y : 10.0, customData : 'value 1' },
{ y : 20.0, customData : 'value 2' },
{ y : 30.0, customData : 'value 3' } ]
}]
} );
However, I noticed that this doesn't quite work in HighStock when your time series is comprised of a large data set (1000+ points).
For example, here is a working fiddle http://jsfiddle.net/gparajon/c5fej775/ (less than 1000 points, which also happens to be the default turboThreshold). And here's the same fiddle, with more data, which breaks the tooltip formatter: http://jsfiddle.net/gparajon/5om258az/
Any workaround?
Thanks!
The error in the console is a bug and it is not really connect why you cannot access extra info in the formatter.
The difference between a chart and a stockchart is that a stockchart does data grouping, what means that in the formatter callback you receive grouped points which does not include extra data (how should they be grouped?).
example: https://jsfiddle.net/g04La2qh/1/
If you disable data grouping, you will receive non-grouped points with extra data.
dataGrouping: {
enabled: false
},
example: https://jsfiddle.net/g04La2qh/2/
I am using laravel 5.1 PHP framework and a sign chart from a javascript, But when i send data from controller with ' (single quote) but JavaScript Parse as some undefined value
$data_B_Temp = "{x : new Date('".$piecesTime[$dataLength]."'), y :".$pieces[$dataLength]."}";
this variable will make a graph point input
as
$(function () {
var chart = new CanvasJS.Chart("TempChart",
{
axisX:{
title: "time",
gridThickness: 2,
interval:1,
intervalType: "hour",
valueFormatString: "hh TT K",
labelAngle: -10
},
axisY:{
title: "distance"
},
data: [
{
type: "line",
dataPoints:[{{$data_B_Temp }}]
}
]
});
$("#TempChart").CanvasJSChart(chart.render());
});
But the javascript executes as :
dataPoints:[{x : new Date('2015-10-30 18:16:08'), y :38.5}]
I'm confused ' is coming? how to solve it?
According to the Laravel Blade documentation, using {{ }} results in an escaped string, which would cause the behavior that you're seeing.
Try using {!! !!} instead; using that syntax will tell Blade to not escape the string.
...
dataPoints: [{!! $data_B_Temp !!}]
...
I'm trying to use Google GeoChart library to display a map, and if I do it on a local HTML file or somewhere like JSFiddle, it works perfectly.
However, when I embed it in a JSP on my project and deploy it (using JBoss), calling chart.draw results in a JSON error:
Invalid JSON string: {":",":",":{":[",","]},":",":{":true}}
My complete Javascript method is as follows:
var data2 = google.visualization.arrayToDataTable([
[{label: 'Country', type: 'string'},
{label: 'description', type: 'string'},
{label: 'consistency', type: 'number'},
{type: 'string', role: 'tooltip'}],
['Canada', "CANADA", 2, "OK"],
['France', "FRANCE", 0, "KO"],
['USA', "USA", 1, "Other"]
]);
var options = {
displayMode: 'region',
backgroundColor: '#81d4fa',
colorAxis: {
colors: ['red', 'orange', 'green']
},
legend: 'none',
tooltip: {
showColorCode: true
}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data2, options);
So it's clearly picking up the "structure" of the JSON object (two simple objects, another object with an array inside, another simple object, another object with an array inside), but for some reason is not picking up the content, except for the 'true' value, so it looks like a problem with quotes...
In any case, I have tried simple and double quotes, removing the quotes from the identifiers, reducing the options object to a simple
var options = {
"legend": "none"
};
... but to no avail. Everything results in a Invalid JSON string error (in this last case, a Invalid JSON string: {":"} error, since there is only one object).
Last note: if I just use
var options = {};
it shows the map (but with the default options).
Any ideas as to why is this happening and/or how to solve it?
Thanks!
I'm trying to draw DB tables using php PDO which i successfully made using the following code:
test.php
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
I need to take the results into a chart JS code which his data array is in this code:
initCharts: function() {
if (Morris.EventEmitter) {
// Use Morris.Area instead of Morris.Line
dashboardMainChart = Morris.Area({
element: 'sales_statistics',
padding: 0,
behaveLikeLine: false,
gridEnabled: false,
gridLineColor: false,
axes: false,
fillOpacity: 1,
data:
[{
period: '2011',
sales: 1400,
profit: 400
}, {
period: '2011 Q2',
sales: 1100,
profit: 600
}, {
period: '2011 Q3',
sales: 1600,
profit: 500
}, {
period: '2011 Q4',
sales: 1200,
profit: 400
}, {
period: '2012 Q1',
sales: 1550,
profit: 5
}],
lineColors: ['#399a8c', '#92e9dc'],
xkey: 'period',
ykeys: ['sales', 'profit'],
labels: ['Sales', 'Profit'],
pointSize: 0,
lineWidth: 0,
hideHover: 'auto',
resize: true
});
}
},
How do i replace the data : [json] with the JSON from the PHP result?
In php file after closing tag you need write JS part, like it
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
Be careful with the semicolon. Just need to correct a little JS script, but I think you can do it.
You would need to echo out the content type, so that browser sees return data and accept as json.
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
I usually open up the google console, or firefox's firebug to see the response tab on the network tab you've sent to. From there, you can see what data you are getting back from server to check if you are echoing right data or not.
Furthermore, you can print them in console log by pluggin
console.log(data);
Within your javascript to confirm whether you are getting data in right format.
You might as well look upon some db document to pull out data just what you need.
Instead of SELECT * FROM pdotable, SELECT period, sales, profit would do.
Hope this helps.
// test.php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
header('Content-type: application/json');
echo $json;
//js
...
if (Morris.EventEmitter) {
//if you use jQuery
$.get('/test.php', {}, function(result) { //or use $.getJSON
dashboardMainChart = Morris.Area({
...
data: result,
...
xmlhttp if you not use jQuery
you only need this json_encode function
this accept an array as parameter and return a string json that you can insert inside a js code simple use echo function
the js code must insert in php file and not in external js
I'm just playing around with jqGrid this afternoon, and have it working fairly well with a local array data source. However, now I'm trying to get it to load local JSON data.
My code is as follows:
jQuery("#list4").jqGrid({
datatype: "json", //<-- Also tried "local" here
height: 'auto',
autowidth: true,
forceFit: true,
colNames:['ID','Name'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int", jsonmap:"id"},
{name:'name',index:'name', width:90, jsonmap: "name"}
],
multiselect: false,
caption: "Test"
});
I then try to load JSON data using the following:
jQuery("#list4").jqGrid.addJSONData(json);
The issue is that jQuery("#list4").jqGrid.addJSONData is undefined. I've also tried:
jQuery("#list4").jqGrid('addJSONData', json);
Which throws an exception saying that the method addJSONData is not defined. I can see other documented methods on jQuery("#list4").jqGrid, just not this one. addXMLData is also missing. However, I can verify that these methods are in the jquery.jqGrid.min.js source code.
I just downloaded jqGrid today, so I know I have the latest versions of everything.
I must be doing something wrong, but I'm not sure what it could be. I've put the entire page here:
http://pastie.org/3825067
The addJSONData is very old method which uses still expandos to the DOM element of the grid (<table> element). So to use addJSONData correctly one should use
jQuery("#list4")[0].addJSONData(json);
See the documentation. More beter way will be to create jqGrid and fill the data directly. You can use
jQuery("#list4").jqGrid({
datatype: "local",
data: mydata,
height: 'auto',
autowidth: true,
colNames: ['ID', 'Name'],
colModel: [
{name: 'id', index: 'id', width: 60, sorttype: "int", key: true},
{name: 'name', index:'name', width: 90}
],
caption: "Test",
gridview: true // !!! improve the performance
});
The format of mydata can be like
var mydata = [
{id: 10, name: "Oleg"},
{id: 20, name: "Mike"}
];
It's allow to use local paging, filtering and sorting of data. The input data need not be sorted.
Alternatively you can use datatype: 'jsonstring' and datastr. The value of datastr can be either JSON string or already parsed object. The data from datastr have to be correctly sorted (if you use some sortname and sortorder parameters) and have the same format as for datatype: 'json' (see the documentation). One can use jsonReader and jsonmap to specify the data format:
var mydata = {
//total: 1, // will be ignored
//page: 1, // will be ignored
//records: 2 // will be ignored
rows: [
{id: 10, name: "Oleg"},
{id: 20, name: "Mike"}
]
];
What is the most strange for me is why you need to load "local JSON data"? Where is the difference to the "local array data source"? You can use $.parseJSON to convert the input data to object or use datatype: 'jsonstring' directly. In the most cases the usage of addJSONData is because of loading the data from the server manually per jQuery.ajax which is really bed idea (see one from my first posts on the stackoverflow here). jqGrid has a lot of customization options and callbackes like ajaxGridOptions, serializeGridData and beforeProcessing, you can use functions in jsonReader (see here) and jsonmap, which allows you to load practically any format of input data. Using prmNames, serializeGridData and postData (see here) you can make practically any customization of the parameters sent to the server. So the usage of low-level addJSONData are needed really in extremely very seldom scenarios.
For the most part, you are close. I don't think the addJSONData method is the way to go. Here's how we deal with local JSON data:
The grid:
$("#list4").jqGrid({
datatype: "local", //<-- "local" tells jqGrid not to try and get the data itself
height: 'auto',
autowidth: true,
forceFit: true,
colNames:['ID','Name'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int", jsonmap:"id"},
{name:'name',index:'name', width:90, jsonmap: "name"}
],
multiselect: false,
caption: "Test"
});
Give data to the grid:
// Clear the grid if you only want the new data
$('#list4').clearGridData(true);
// Set the data the tell the grid to refresh
$('#list4').setGridParam({ data: jsonData, rowNum: jsonData.length }).trigger('reloadGrid');
You should also change your jsonData to:
var jsonData = [
{id: 1, name: 'Apple'},
{id: 2, name: 'Banana'},
{id: 3, name: 'Pear'},
{id: 4, name: 'Orange'}
];
jqGrid is going to look to match up the columns specified to the objects passed into the array.
I'm working with version jqGrid 4.1.2
Having initialized the grid with a JSONReader and datatype:'jsonstring', when adding jsonstring data I've to include the datatype:'jsonstring' parameter.
$('#list4').setGridParam({ datastr: jsonData, datatype:'jsonstring', rowNum: jsonData.length }).trigger('reloadGrid');
As far as I know that is because after initialize the datatype:'jsonstring' is turned to datatype:'local', so when adding jsonstring it tries to load data from "data" param instead of "datastr" but because is empty no data is loaded.
I hope to contribute to this ...