passsing data to https by JSON using JSONP - json

i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`

Related

How to fix SyntaxError: Unexpected token &

I am sending a php coded in accordance with the json_encode function to a plantilla.twig where I want to graph a pie chart type and the browser shows me the following error in console uncaught SyntaxError: Unexpected token & ¨ and I red the line following data: [[& quot; Intermediate 17.5 inches & quot;, 2220]]
Controller Class
public function tiempoXEtapaAction()
{
$em = $this->getDoctrine()->getManager();
$servicepozo = $this->get('service.pozo');
$pozoActual = $servicepozo->getPozoActual();
$idpozo = $servicepozo->getPozoActual()->getId();
$activityCollections = $em->getRepository('ActividadBundle:ActividadDiariaCollection')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$intervalos = $em->getRepository('IntervaloBundle:Intervalo')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$actividades = $em->getRepository('ActividadBundle:ActividadDiaria')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$tiempoXIntervalo = array();
foreach ($activityCollections as $activityCollection) //Dias
{
$fechaActCole = $activityCollection->getFecha();
foreach ($intervalos as $intervalo) //Intervalos
{
if ($intervalo->getFechaInicio() <= $fechaActCole && $intervalo->getFechaFinal() >= $fechaActCole) {
$temp = array();
$temp[] = $intervalo.'';
foreach ($actividades as $actividad) //Actividades
{
if ($actividad->getCollection()->getId() == $activityCollection->getId()) {
$duracion[] = $actividad->getDuracion();
}
}
$temp[] = array_sum($duracion);
}
}
$tiempoXIntervalo[] = $temp;
}
return array('tiempoXIntervalo'=> (json_encode($tiempoXIntervalo)));
Template.Twig
title: {
text: 'Distribución de tiempo por Intervalo'
},
xAxis: {
reversed: false,
title: {
enabled: true,
text: 'Dias'
},
labels: {
formatter: function () {
return this.value;
}
},
maxPadding: 0.05,
showLastLabel: true,
allowDecimals: false,
min:0,
},
yAxis: {
max:0,
startOnTick: false,
title: {
text: 'Profundidad [m]'
},
labels: {
formatter: function () {
return this.value;
}
},
lineWidth: 2,
},
legend: {
enabled: true
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}h ({point.percentage:.1f}%)</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
data:{{tiempoXIntervalo}}
}]
});
});
</script>
You should check how to convert HTML entities
Also, there is an extra space in & quot;
It should be "
json_encode expects " so it should be ["Intermediate 17.5 inches",2220]
Thanks Fernando but your solution do not work for mi.
Apparently the problem was Twig autoescaping variables. I tried to use Twig's raw filter to skip autoescaping and it's work for mi. Here the solution
data: $.parseJSON('{{ tiempoXIntervalo | raw }}')

Get current day values from database to plot on highcharts

Hello i am designing a webserver which shows me a power consumption graph from a mysql database. I am a beginner and have written a code with some help that uses ajax calls to fetch the data from the database and plot it on the highcharts. Problem is that I get all the historic values saved in my database but I want only the values of current day to be plotted on the chart. This is my js code:
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'area',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100
},
yAxis: {
title: {
text: 'POWER'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%d-%m-%Y %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Power Consumption',
data: (function () {
var data = [], i, t, d;
var request = {};
request['EndPoint'] = "arduino/charts/analog/fetch";
$.ajax({
type: "POST",
url: "../Server/fyp-processor.php",
data: JSON.stringify(request),
dataType: "json",
async: false,
success: function (result) {
if(result.Code == "1008" && (result.Data != null || result.Data != undefined)) {
for(i = 0; i < result.Data.Historic.length; i++) {
t = result.Data.Historic[i].DateTime.split(/[- :]/);
d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.push({
x: d,
y: parseInt(result.Data.Historic[i].Value)
});
}
}
}
});
return data;
}())
}]
});
It calls a fyp-processor php script that contains this code:
else if($postData['EndPoint'] == 'arduino/charts/analog/fetch') {
#result set
$resultSet = null;
#get all historic analog chart data
$results = $db->charts();
if(count($results) > 0) {
foreach($results as $result) {
$resultSet['Historic'][] = $result;
}
}
I would be glad if anyone could help me out to get only current DAY's data and also what changes I can do to it then to get current month and current week's data too.

HighCharts issues in Dual axes, line and column charts

I am trying to generate Dual axes, line and column charts of highcharts .I have tried stackoverflows sugesstions but i couldn't find proper solution.I have the data formatted properly but yet the chart is not generate shows blank.I want this type of [link] http://jsfiddle.net/sunman/dwyNz/8/ .In spline line I want to show 'bsp values' and in column I want to show facilities_total. So below i show my code for this graph.I also pointed my error in index.php.
Here is my Index.php
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Project faclityv Rating'
},
subtitle: {
text: 'testing'
},
xAxis: [{
categories: []
}],
yAxis: [{ // Primary yAxis
labels: {
// format: '{value} Rs.',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Bsp Cost',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'facility rating',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
//format: '{value} out of 100',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Facility Rating',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
valueSuffix: ' out of 100'
}
}, {
name: 'Bsp Cost',
type: 'spline',
data: [],
tooltip: {
valueSuffix: 'Rs.'
}
}]
});
$.getJSON("combochart.php", function(json) {
options.xAxis.categories = json[0]['data']; /*error here: ReferenceError: options is not defined */
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
Here is my combochart.php
$query1 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id ");
$category = array();
$category['name'] = 'Project';
while($row1 = mysql_fetch_array($query1)) {
$category['data'][] = $row1['Project_name'];
$series1['data'][] = $row1['faci_total'];
}
$query2 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id
LEFT OUTER JOIN cost ON gsuperfac_rating.project_id=cost.project_id ");
$series1 = array();
$series1['name'] = 'Project Name';
$series2 = array();
$series2['name'] = 'BSP VALUES';
while($row2 = mysql_fetch_array($query2)) {
$series1['data'][] = $row2['faci_total'];
$series2['data'][] = $row2['bsp'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
I think i have problem in json code thats why i can't fetch data for graph.i checked in my console no errors.but i debug this code and json result shows me(json o/p writes in jsfiddle) but graph not appear in browser. i am explained in jsfiddle[link] jsfiddle.net/sunman/rDYvt/9 please check this. give me solution where i am wrong.So please help me and resolve my query.
Inside your $.getJSON("combochart.php", function(json) you need to setData like this
theChart.xAxis[0].setCategories(json[0]['data']);
theChart.series[0].setData(json[1]['data'], false);
theChart.series[1].setData(json[2]['data'], true);
Ok, it's working now...
Paste this in a JSFiddle to see it working...
$(document).ready(function() {
var json= '[{"name":"Project","data":["Green View","Grand","Arete","Canary Greens","Terra","Beethovens","Ninex City","South Park","Callidora","Lotus","Coban","NCR Green","Kocoon","Estella","NCR One"]},{"name":"Facilities Rating","data":[45,55,55,55,55,55,55,55,55,55,55,55,55,55,55]},{"name":"BSP VALUES","data":[97500,55745,16400,98700,38600,12090,94700,11400,12450,89500,86725,88335,54200,18200,30400]}]'
var jsobj = JSON.parse(json)
var firstSeriesData = [];
var secondSeriesData = [];
jsobj[1].data.forEach(function(seriesOneData){
firstSeriesData.push(seriesOneData);
})
jsobj[2].data.forEach(function(seriesTwoData){
secondSeriesData.push(seriesTwoData);
})
$('#container').highcharts({
chart: {
zoomType: 'xy',
type: 'column',
marginRight: 130,
marginBottom: 50
},
title: {
text: 'Top 12 Projects Facilities Rating and BSP Costs ',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: jsobj[0].data
},
yAxis: {
min: 0,
title: {
text: 'Facilities Rating'
},
plotLines: [{
value: 0,
width:1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
plotOptions:{
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color:'white'
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
borderWidth: 0,
x: -10,
y:110
},
series: [ {
name:'Facilities Rating',
data:firstSeriesData,
id:'dataseries'
},{
name:'BSP',
type:'spline',
data:secondSeriesData
}]
})
});
A couple comments.. your JSON had an unidentified character in it. This is what I got from pasting your JSON string.
Notice that red dot in the middle of the JSON.
Also, make sure you load highcharts modules in this order...
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
And lastly, you have two series in there, but one of them has values below 100 and the other one has values over 100k. So the first series is not gonna show as it almost 0 compared to the second. You'll have to do something about that.
In your function $.getJSON("combochart.php", function(json) you need to explicitly define what options you want. You are also not acutally setting any data. I am assuming that json[0]['data'] is a list of categories like ['Cat1', 'Cat2',...] and that json[1] and json[2] contain the data like [val1, val2, ...]. If so you need to do something like this:
$.getJSON("combochart.php", function(json) {
var theChart = $('#container').highcharts();
theChart.xAxis[0].setCategories(json[0]['data']); /*error here: ReferenceError: options is not defined */
theChart.series[0].setData(json[1]);
theChart.series[1].setData(json[2]);
//chart = new Highcharts.Chart(options);
});
});

Highcharts bargraph from json data in angularJS

I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>

Highchart not displaying json data

I can't figure out what I'm doing wrong with my Highchart. It's supposed to read a json array, (really just a date, and a y value and plot it to a chart. However, I can't seem to get any points to plot to a chart. What am I doing wrong?
php code:
$statement = "select count(title) from node where title like 'WEN%'";
$result = mysql_query($statement);
while ($row = mysql_fetch_array($result)) {
$data = $row['count(title)'];
}
$x = time() * 1000;
$y = $data;
$array = array($x,$y);
echo json_encode($array);
html/javascript code:
<p>Chart</p>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
<script>
function requestData() {
jQuery.ajax({
url: 'queryp.php',
datatype: 'json',
success: function(point) {
var series = chart.series[0];
// add the point
chart.series[0].addPoint(point, true);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
</script>
<script type="text/javascript">
jQuery(function () {
jQuery(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: requestData
}
},
title: {
text: 'Live Query Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Query Data',
data: []
}]
});
});
});
</script>
</div>
Your series[0] object has no method named addPoint, you should see this in the console.
If you want to append to the data array, just use push
chart.series[0].data.push(point[1]);
The problem is that you are referencing to chart variable, which is not ready yet - you are using load event handler. Use something like this:
function requestData() {
var series;
if(chart.series[0]){
/* all other cases load chart */
series = chart.series[0];
} else {
/* first load chart */
series = this.series[0];
}
jQuery.ajax({
url: 'queryp.php',
datatype: 'json',
success: function(point) {
series.addPoint(point, true);
setTimeout(requestData, 5000);
}
});
}
Also, make sure that values are numbers. Not strings.