Google Dynamic Chart not loading data using JSON - mysql

I am trying to make a dynamic google chart using information from MYSQL DB, I have to pages one draws the information from the DB using json and the other should use the information and create the chart
$query = "SELECT * FROM woodford_fuel";
$result = $conn->query($query);
$jsonArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['reg'];
$jsonArrayItem['value1'] = $row['consump_100'];
array_push($jsonArray, $jsonArrayItem);
}
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
With this I get the following Result, the values I am getting is correct
[{"label":"ND230819","value1":"50.55"},{"label":"ND866941","value1":"51.15"}]
I am trying to load the Chart with the following script
function drawLineChart() {
$.ajax({
url: "chart_data.php",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrSales = [['label', 'value1']]; // Define an array and assign columns for the chart.
// Loop through each data and populate the array.
$.each(data, function (label, value1) {
arrSales.push([value.label, value.value1]);
});
// Set chart Options.
var options = {
title: 'Average Consumption',
curveType: 'function',
legend: { position: 'bottom', textStyle: { color: '#555', fontSize: 14} } // You can position the legend on 'top' or at the 'bottom'.
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(arrSales)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
It is not showing me any chart at all

Related

Displaying JSON data into a pie chart using chart.js

my first time using chart.js and am running into a small bug that I can't seem to work around it. Below is my code, however, its just displaying the labels but not rendering the pie chart itself.
Am following samples from the chart.js documentation here http://www.chartjs.org/docs/#doughnut-pie-chart-example-usage
Your help will be appreciated.
<canvas id="myChart" width="200" height="200"></canvas>
$(document).ready(function () {
/*
-> #47A508 = green (wins)
-> #ff6a00 = orange (losses)
-> #ffd800 = yellow (draws)
*/
var DataArray = [];
var ctx = document.getElementById("myChart");
$.ajax({
url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
dataType: 'json',
type: 'GET',
}).done(function (result) {
$.each(result.standing, function () {
var name = "Manchester United FC";
if (this.teamName == name) {
DataArray.push([this.wins, this.losses, this.draws]);
}
});
var myChart = new Chart(ctx, {
type: 'pie',
data: {
label: 'Manchester United Current Form',
labels: [
"Wins",
"Losses",
"Draws"
],
datasets: [
{
data: DataArray,
backgroundColor: [
"#47A508",
"#ff6a00",
"#ffd800"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
},
options: { responsive: true }
});
});
}
maybe it is because of the jquery each, it fills DataArray async and the array is not ready, when you want to use it as chart data.
Change the $.each to a simple js for loop
for(var i = 0; i < result.standing; i++){
var name = "Manchester United FC";
var team = result.standing[i];
if (team.teamName == name) {
DataArray.push(team.wins, team.losses, team.draws);
}
}
try callbacks for you ajax or do the below (which is a dirty solution):
$.ajax({
url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
dataType: 'json',
cache: false, //add this
async: false, //add this
type: 'GET',
Also
the result of your ajax could be returned using the below code instead of using an array.
jQuery.parseJSON(result);
The issue lies in your DataArray. The way it is implemented is is an array with a single entry. Which is another array itself.
[[<wins>, <losses>, <draws>]]
instead of
[<wins>, <losses>, <draws>]
That is because you instantiate an array and then push into it an array object.
To fix this try using the following function:
(...)
$.each(result.standing, function () {
var name = "Manchester United FC";
if (this.teamName == name) {
DataArray = ([this.wins, this.losses, this.draws]);
console.log("This team name");
}
});
(...)
I got this solved, well sadly, with no magic at all to brag about. There was nothing wrong with the code initially, however, it was a problem with the DOM rendering performance. Thank you #alwaysVBNET and #Aniko Litvanyi for your inputs as well.
This link helped me out, hopefully it does to someone out there.

load dynamic dropdownlist with json function but not working on ie 11

i have a function that works well in firefox and chrome But no in ie11, the problem is that the dropdown lists are showing empty and not data are coming to the select boxes.. :( please some help guys cause i m trying for ages to solve this with no lack..
my function is the following
function loadDynamicDdl(ajaxUrl , ddlId) {
$.ajax({
dataType:'json',
type: 'GET',
url: ajaxUrl,
cache:false,
async:false,
success:function (response) {
var ddl = $('#' + ddlId);
ddl.empty();
var opts = response.Options;
$.each(opts, function(i, item) {
ddl.append($("<option />").val(item.Value).text(item.DisplayText));
});
},
error:function (jqXHR, exception) {
//alert("There was an error loading dropdownlist.");
}
});
}
why omg is not working in internet explorer 11 ??? why,,, please guys i m about to break my head on the keyboard.. thank you in advance..
function loadDynamicDdl(ajaxUrl , ddlId) {
$.ajax({
dataType:'json',
type: 'GET',
url: ajaxUrl,
cache:true,
// contentType: "application/x-www-form-urlencoded;charset=UTF-8",
async:false,
success:function (response) {
if (response.Result == 'ERROR') {
$('#system-message-container').html('<h2 style="color:red;">' + response.Message + '</h2>');
$('#maincontent-container').hide();
}
var ddl = $('#' + ddlId);
ddl.empty();
var opts = response.Options;
//Not working when we have duplicates in json
// $.each(opts, function(i, item) {
// ddl.append($("<option />").val(item.Value).text(item.DisplayText));
// });
//Start checking for duplicates numbers in the Value field and DisplayTexts in json and push the uniques
var finalResult = [];
var Values =[];
var DisplayTexts = [];
$.each(opts, function (i, value) {
if ($.inArray(value.DisplayText, DisplayTexts) == -1 && ($.inArray(value.Value, Values) == -1)) { // it returns -1 when it doesn't find a match
Values.push(value.Value);
DisplayTexts.push(value.DisplayText);
finalResult.push(value);
ddl.append($("<option />").val(value.Value).text(value.DisplayText));
}
});
},
error:function (jqXHR, exception) {
//alert("There was an error loading dropdownlist.");
}
});
}

How to get multiple data series into Highcharts

The following code works:
var options1 = {
chart: {
renderTo: 'container1'
},
series: [{}]
};
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
var chart = new Highcharts.Chart(options1);
});
I want to be able to add a number of data series, so I am trying to take the reference to ‘new Highcharts’ out of the getJSON, but I don't seem to get it right. This following code does not work:
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
});
var chart = new Highcharts.Chart(options1);
I have also tried tackling it a different way but again the following code does not work:
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1'
},
series: [{}]
});
$.getJSON('tokyo.jsn', function(data){
chart1.series[0].data = data;
});
Can anyone point me in the correct direction. I need to be able to support multiple data series by doing a second getJSON call like the following:
$.getJSON('sydney.jsn', function(data){
options1.series[1].data = data;
});
The JSON code I'm using is as follows:
[ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]
Thanks
$.getJSON is an asynchronous request. Once you receive the data, then you can pass it to Highcharts, thus you have to call that code from within the callback function of $.getJSON().
Try this, use a helper function to process your data and draw the chart, see drawChart() below:
var options1 = {
chart: {
renderTo: 'container1'
},
series: []
};
var drawChart = function(data, name) {
// 'series' is an array of objects with keys:
// - 'name' (string)
// - 'data' (array)
var newSeriesData = {
name: name,
data: data
};
// Add the new data to the series array
options1.series.push(newSeriesData);
// If you want to remove old series data, you can do that here too
// Render the chart
var chart = new Highcharts.Chart(options1);
};
$.getJSON('tokyo.jsn', function(data){
drawChart(data, 'Tokyo');
});
$.getJSON('sydney.jsn', function(data){
drawChart(data, 'Sydney');
});
See fiddle: http://jsfiddle.net/amyamy86/pUM7s/
You can use solution used by Highcharts in that example: http://www.highcharts.com/stock/demo/compare
Or first create empty chart, without any series, and then use addSeries() function in each callback, see: http://api.highcharts.com/highcharts#Chart.addSeries()

Highchart Basicline

According to my own question
i have tried something, and my fiddle is link
But i want to be output as like below
i.e x axis contains monthly reports
my ajax code is
$.ajax({
url: "/echo/json/",
data: data,
type: "POST",
success: function(point) {
var chartSeriesData = [];
var chartCategory = [];
$.each(point, function(i, item) {
var series_name = item.resultDate;
var series_data = item.y;
var cagory = series_name;
var series = {
name: series_name,
data: item.y
};
chartSeriesData.push(series);
chartCategory.push(series_name);
});
var chartingOptions = {
chart: {
renderTo: 'container',
defaultSeriesType: 'spline'
},
xAxis: {
categories: chartCategory
},
series: chartSeriesData
};
chartingOptions = $.extend({}, jugalsLib.getBasicChartOptions(), chartingOptions);
chart = new Highcharts.Chart(chartingOptions);
}
});
Thanking you....
In your parser, you create many series, because you initialize series in points loop. So you should prepare series earlier than points loop. Then add points to correct serie (in this case first or second serie).

Add JSON value to ko.computed in viewmodel

I am busy creating a currency Module for my web app, I am using Yahoo Finance API to return the currency conversion rate of 2 currencies that I have defined in my local DB. I get the JSON data fine from the API, I just want to Bind the JSON data that I have received from the Finance API to my existing Viewmodel using ko.computed. I am not sure if I should be using ko.computed to achieve this, so any advice will help greatly.
Here is my code:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.computed(rates); // I WANT TO BIND THE VALUE FROM API HERE
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedCurrencies =
$.map(Result.d,
function (item) {
getRate(item.CurrencyFrom, item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result from Yahoo Finance API
function getRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=rates"); //HERE I CALL THE VALUE TO OBTAIN THE CONVERSION RATE FROM API
document.body.appendChild(script);
}
//I WANT TO ADD THIS TO MY VIEWMODEL
var rates = function parseExchangeRate(YahooData) {
var rate = YahooData.query.results.row.rate;
}
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
$('[rel=tooltip]').tooltip();
})
The JSON returned from parseExchangeRate Function (Yahoo Query Result):
parseExchangeRate({"query":{"count":1,"created":"2013-01-18T06:46:41Z","lang":"en-US","results":{"row":{"rate":"0.1129","name":"ZAR to USD"}}}});
I see you're already using jquery so I'll use jquery for the JSONP too. I'm using a simple ko.observable for the conversion rate, and added a "bare" ko.computed that does the ajax request and asynchronously updates the observable. Let me know if you need any further clarification.
JSFiddle example (with mock data instead of your initial ajax): http://jsfiddle.net/VsW5H/1/
Updated code:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(data.ConversionRate);
ko.computed(function () {
var from = self.CurrencyFrom(),
to = self.CurrencyTo();
if (!from || !to) {
self.ConversionRate("N/A");
return;
}
getRate(from, to).done(function (YahooData) {
console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
self.ConversionRate(YahooData.query.results.row.rate);
});
});
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push(new currency({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
}));
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedCurrencies = $.map(Result.d,
function (item) {
return new currency(item);
});
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result from Yahoo Finance API
function getRate(from, to) {
return $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=?");
}