Create highcharts chart using AJAX/JSON - ajax

I am building a website that uses the Highcharts library to display a single line series chart. I am using AJAX to retrieve historical financial data from yahoo finance using their YQL.
The ajax call is working correctly and I can view the returned data in the console for example
console.log( data.query.results.quote[0].Close );
returns the closing price value 457.84
How do I now build the single line series chart using this data?
I cannot find a simple explanation anywhere of how to create the chart using AJAX data.
Thanks
edit: I am fetching the data in AJAX and it works correctly but trying to make the chart work with JSON is where im having difficulties.
This is what my code currently looks like: http://jsfiddle.net/JbGvx/
This is the demo code off the HighStocks website: http://jsfiddle.net/xDhkz/
I think the problem is with the date formatting of the AJAX request. The date is being returned like so 2013-02-25 but the chart wants JS timestamps. Is there a way that I can extract the date from the AJAX, convert it using Date.UTC and then make the chart using the converted data?

If you are considering stock data, consider using HighStocks instead of HighCharts. It can handle many data points much faster than HighCharts is able to.
HighStocks has an example where they pull in AJAX data (1.6 million points) asynchronously here: http://www.highcharts.com/stock/demo/lazy-loading

var chartSeriesData = [];
var chartCategory = [];
$.each(response, function() {
if(this.name!="TOTAL" && this.no!="0")
{
var series_name = this.name;
var series_data = this.no;
var series = [
series_name,
parseFloat(series_data)
];
chartSeriesData.push(series);
}
});
//initialize options for highchart
var options = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'SalesOrder '
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
center:['60%','60%'],
size:150
,
dataLabels: {
enabled: true,
color: '#000000',
distance: 40,
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.y} '
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data:chartSeriesData //load array created from json
}]
}
//options.series[0].setData(datavaluejson);
var chart= $('#container').highcharts(options);

Related

Export to PDF increase number of items per page

I have a grid control which I wish to export the content of. Upon initialisation, the pageSize attribute is set to 10 items however I want to increase the number of items per page during exportToPDF.
I have tried to modify the pageSize of the dataSource prior to carrying out the export but this seems to have no effect on the end product.
var grid = $("#grid").data("kendoGrid");
var filter = grid.dataSource.filter;
grid.dataSource.query({
filter: filter,
pageSize: 20, // has no effect on the exported PDF
page: 1,
group: [{
field: "groupField1",
dir: "asc"
}, {
field: "groupField2",
dir: "asc"
}, {
field: "groupField3",
dir: "asc"
}]
});
var progress = $.Deferred();
grid._drawPDF(progress)
.then(function (root) {
return kendo.drawing.exportPDF(root, { forcePageBreak: ".page-break", multiPage: true });
})
.done(function (dataURI) {
// ... do some manual manipulation of dataURI
kendo.saveAs({
dataURI: manipualtedDataURI
});
progress.resolve();
Is there something I am missing so I can display more items on each page of the PDF export?
EDIT
Including my grid definition with the pdfExport function suggested by the below answer (which never gets called):
var grid = $("#reportGrid").kendoGrid({
pdf: {
allPages: true,
avoidLinks: true,
repeatHeaders: true,
template: kendo.template($("#page-template").html()),
scale: 0.7,
margin: { top: "2.5cm", right: "1cm", bottom: "1.5cm", left: "1cm" },
paperSize: "A4",
landscape: true
},
// *this function is not getting called*
pdfExport: function(e) {
e.sender.dataSource.pageSize(10);
e.promise.done(function() {
e.sender.dataSource.pageSize(20);
});
},
toolbar: kendo.template($("#template").html()),
...
});
Note: A template is used to include a header / footer on each page of the PDF export.
Another note: 'Manual manipulation of dataURI' includes going out to the server to perform a merge with another PDF file, so I cannot use the default export via the grid :(
EDIT 2
I have extended the Dojo example from #R.K.Saini's answer to use the method by which I need to generate the PDF export (as per original post).
The snippet logs the URI of the grid being exported and when the pdfExport function is called. As you will see, when using the built in grid 'Export to PDF' button, the pdfExport function is triggered but when using the additional button below the grid, it is not.
You can use pdfExport event to change page size of your grid datasource before pdf export started and then when the export finish you just need to revert back the previous page size.
The call back function of this event receive grid instance as e.sender and and a promise as e.promise which can be used to set back the page size when exporting finish.
For more info check http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-pdfExport
$("#grid").kendoGrid({
dataSource: dataSource,
pdf: {
allPages: true
},
pdfExport: function(e) {
e.sender.dataSource.pageSize(10);
e.promise.done(function() {
e.sender.dataSource.pageSize(20);
});
},
...
//Other configguration
});
Here is a working demo http://dojo.telerik.com/UzOXO
Edit
You can also change grid page size in your custom export function just change grid page size before calling _drawPdf() function and change it back when done.
$("#btnPdfExport").kendoButton({
click: function () {
var grid = $("#grid").data("kendoGrid");
var progress = $.Deferred();
// Change grid datasource pagesize before calling _drawPDF
grid.dataSource.pageSize(20);
grid._drawPDF(progress)
.then(function (root) {
return kendo.drawing.exportPDF(root, { forcePageBreak: ".page-break", multiPage: true });
})
.done(function (dataURI) {
console.log("Exporting " + dataURI);
kendo.saveAs({
dataURI: dataURI,
fileName: "export.pdf"
});
progress.resolve();
// Change grid datasource pagesize when done
grid.dataSource.pageSize(10);
});
}
});
Check Update DOJO here http://dojo.telerik.com/UzOXO/8

Using C3.js, when loading data via URL/JSON, is there a way to include groups in the data?

If I'm creating a C3.js graph using:
var chart = c3.generate({
bindto: '#my-chart-div',
data: {
url: '/data/data.json',
mimeType: 'json',
type: 'area',
groups: [
['thing1', 'thing2', 'thing3']
]
},
});
Is there a way for me to include the groupings (thing1, etc) in the URL-loaded JSON data?
I couldn't find a way to include groups in JSON data.
The best work-around I found to to this was using the onrendered callback, and inside that callback, retrieve the data headers from the chart itself, then apply them in the grouping you want using groups:
onrendered: function () {
if ( $('#chart-div').data('stacked') != true ) {
chart.groups( [ chart.data().map(function(x){return x.id}) ]);
$('#chart-div').data('stacked', true);
}
}
Note the line that checks to see if the chart has already been stacked - applying a grouping to the chart re-renders it, which triggers this callback again (prevents an infinite loop).

Kendo grid data source update approach not working

I have JSON data flowing via Pusher to a simple MVC5 website housing a Kendo Grid. The data, upon arrival, renders successfully in the grid however I'm creating and setting the data source every time. As this seems sinful, I'm trying to determine why my approach to simply updating the data source doesn't render the data.
The grid:
<div id="dashboard"></div>
<script>
$(document).ready(function () {
$("#dashboard").kendoGrid({
columns: [
{ field: "SystemName", width: "50px", title: "System" },
{ field: "Description", width: "100px", title: "Description" },
{ field: "SystemStatus", width: "30px", title: "Status" }
],
height: 600,
scrollable: true,
sortable: true,
});
var dataSource = new kendo.data.DataSource();
var grid = jQuery("#dashboard").data("kendoGrid");
grid.setDataSource(dataSource);
})
</script>
My failed attempt to read in the data without creating and binding a new data source (body of a function call which does happen):
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data = array;
grid.dataSource.read(array);
grid.refresh();
I have confirmed that the data arrives from Pusher correctly yet the above approach does not update the grid.
Thanks in advance for any consideration.
jbt
Use the data() method on the dataSource to set it's data.
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data(array);
You can only set the string value of data on the dataSource if the source is of XML type. Since you are using JSON, you need to call the data function and pass in the new data.
See documentation... http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-data

How to reduce data table load time?

I am working with data table plugin. Initially what I tried is to update the data table plugin from a flat text file. The text file would look like below.
{
"data":[
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
},
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
}
]
}
I have a HTML file inside this I am writing JavaScript like below.
$(document).ready(function() {
var table=$('#app-table').DataTable( {
"bProcessing": true,
"bPaginate":true,
"bServerSide": false,
"sAjaxSource": "./data/arrays.txt",
"deferRender": true,
"columns": [
{ "data": "reference" },
{ "data": "application" },
{ "data": "applicationType" },
],
"order": [[ 3, "desc" ]],
"ordering": true,
"bFilter": true
} );
The data table is rendering fine until am not having more than 20,000 rows in the table. As the number of rows will increase in the table then data table took more time to load.
What I notices by going through with several site is that we can reduce the load time by using server side processing and for that I need to go with a server which is not possible in my case because I am rendering data from a flat text file. Then I thought to look for static data storage.
So coming to the problem is using indexedDB can we resolve the performance issue and if answer is yes than can anyone let me know how?
I am able to work with indexedDB but unable to integrate with jQuery data table. I mean what I need to make change in the JavaScript. If we can make server side processing with indexedDB then what will be the script?
first read your local file in the following manner:
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
Then, use JQuery to parse "allText" into JSON.
Refer this link for parsing into JSON.
Now, create database using "indexedDB API" as mentioned below:
var request = indexedDB.open("<mention_your_db_name_here");
request.onupgradeneeded = function() {
// The database did not previously exist, so create object stores and indexes.
var db = request.result;
var store = db.createObjectStore("books", {keyPath: "reference"});
var titleIndex = store.createIndex("by_reference", "reference", {unique: true});
// Populate with initial data.
store.put({reference: "#VIP-123", application: "Development Aspects", applicationType: "Current Application"});
};
request.onsuccess = function() {
db = request.result;
};
for more details on "indexedDB API", please refer this link

Extjs How to access the name of the chart being used by store

I have a store being used by several charts. I get my data remotely with an ajax call. In the php script that I link it too, I'm just going to change the parameters of my query to adjust for the different charts.
Here's my idea: I pass the title of the chart's panel as a parameter to my php script. That'll tell me which chart it is.
How do I access the title of whatever chart the store is being used by?
var my_store = Ext.create('Ext.data.JsonStore', {
fields: ['project', 'accepted', 'rejected', 'deleted', 'undefined'],
proxy: {
type: 'ajax',
url: 'generate_proj.php',
extraParams: {foo: **chart.id**},
reader: {
type: 'json'
}
},
autoLoad: true,
listeners: {
beforeload: function(store,operation) {
//operation.params.foo = this.idname;
},
load: function(obj,records) {
var text = Ext.decode(obj.responseText);
Ext.each(records,function(rec) {
});
}
}
});
Here's what I've done so far. Getting the name of a single chart/panel is no problem. I want the store to be able to dynamically read the name of what's using it. How?
Somewhere, you have some code that switches between the various charts. During that code, you could do something like
activeChart.getChartStore().proxy.extraParams.foo = activeChart.getId();
where activeChart is whatever reference you have to the chart you are about to show. Then when you load the store, it'll send the correct parameter.

Resources