How to fetch data from DB on Chart.js using Laravel? - laravel

I want to show data from database on chart and I have shown return response I need to fetch on chart but I don't know how to do that does anyone have an idea?
Return response:
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
Chart script:
<script>
var barChartData = {
labels: ['Joylinhk', 'HorizonTechnologies','Alahazrat','j2w'],
datasets: [{
label: "",
backgroundColor: window.chartColors.blue,
data: [13, 2,9,0],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Project Report Chart'
}
,
tooltips: {
mode: 'index',
intersect: false
}
,
responsive: true,
scales: {
xAxes: [{
stacked: true,
}
],
yAxes: [{
stacked: true
}
]
}
}
}
);
};
</script>

I do This more than one time
first of all you should Include Google Chart in Your Blade File
Let's See The controller function that return data to the chart
I make a function called getAreaChart()
public function getAreaChart():array {
$data = DB::table('companies')->get();
$array[]=['area','counts'];
foreach ($data as $key=>$da):
$array[++$key] = [Area::find($da->area)->area,intVal($da->count)];
endforeach;
return $array;
}
for the function that return data to view and displayed in chart, I call the function and don't forget to json_encode the result
public function home()
{
$array = $this->getAreaChart();
return view('admin.home')->with('companies', json_encode($array));;
}
in the blade file , I make a div with id pie_chart
<div id="pie_chart" style="width:510px; height:408px;background: transparent">
and the script should be like this
<script type="text/javascript">
var analytics = <?php echo $companies; ?>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable(analytics);
var options = {
title : ''
};
var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
chart.draw(data, options);
}
</script>
You can change the chart by change the value corechart see google chart doc
this is example that I follow
Google Charts Docs
google.charts.load('current', {'packages':['corechart']});
and this is the google charts types
Google Charts Types
I hop that helpful ;)
happy code

Related

How to use values from an ajax request in google charts?

I am creating an array of objects using Ajax to use as values in a google line chart, however the values do not render even though I can view them through the console.
I have tried using ajax complete function to call the charts once the values are set but it still doesn't work, I suspect it's due to scoping but I don't know how to resolve it. here is my code
complete array
studentCount[
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
}
{
month:5,
count:4
}
etc...
]
code
$.ajax({
dataType: "json",
url: url,
success: function (data) {
for (var i = 0; i < data.length; i++) {
studentCount[data[i].month -1].count = data[i].count;
}
}
});
$( document ).ajaxComplete(function() {
google.charts.load('current', {
packages: ['line']
});
google.charts.setOnLoadCallback(drawLineColors);
console.log(JSON.stringify(studentCount[0].count)) //returns correct value
function drawLineColors() {
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count],
['June', studentCount[5].count],
['July', studentCount[6].count],
['August', studentCount[7].count],
['Septembre', studentCount[8].count],
['October', studentCount[9].count],
['November', studentCount[10].count],
['December', studentCount[11].count]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
recommend loading google first, you can include the callback directly in the load statement
once loaded, then call ajax
see following working snippet, adjust as needed to get proper data,
and change error to success as the url isn't reachable from here...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
},
packages: ['line']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
also, recommend using core chart instead of material,
several config options simply don't work with material charts
core chart, use package --> corechart
and chart --> google.visualization.LineChart
you can use config option theme: 'material' to get the core chart close to the look and feel of a material chart
see following working snippet...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437'],
theme: 'material'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How can I generate a real-time highchart from my database data?

I have looked at the following links Binding json result in highcharts for asp.net mvc 4 , highcharts with mvc C# and sql, HighChart Demo and many others. However, I couldn't find a working demo showing how to implement a highchart using data from a database.
Objective:
I want to generate a real time highchart line graph getting data from my database. What I want is very similar to the third link which provides a real-time highchart with randomly generated values. It is also similar by X-axis and Y-axis, for I want my x-axis to be "Time" (I have a DateTime column in my database) and y-axis to be an integer (I have a variable for that as well in my database).
Please I need help in sending the model data to my razor view.
Note that I am already using SignalR to display a realtime table. I also want to know if it can be used to automatically update the highchart as well.
Below is the code snippet of my script in the view. I have used the code provided in link 3 for generating the highchart. Please tell me where should I apply the changes on my code.
#section Scripts{
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
//Highchart
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Fill chart
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);//300000
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessages',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
$("#g_table").dataTable();
}).error(function (e) {
alert(e);
});
}
</script>
}
UPDATED CODE
//Highchart
Highcharts.setOptions({
global: {
useUTC: false }
});
//Fill chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: $.connection.hub.start().done(function () {
alert("Chart connection started")
var point = getAllMessagesforChart();
var series = this.series[0];
setInterval(function (point) {
// add the point
series.addPoint([point.date_time, point.my_value], true, true)
}, 1000);
}).fail(function (e) {
alert(e);
})
}
}
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
function getAllMessagesforChart() {
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessagesforChat',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (data) {
data = JSON.parse(data);
//data_graph = [].concat(data);
//$("#debug").html(data_graph);
}).error(function (e) {
alert(e);
});
return data;
//return data_graph;
}
There is an example that might help you:
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/
it uses an ajax callback function.
Well, you can also have a look at my sample where I add dynamically series by clicking add button.
http://plnkr.co/edit/Sh71yN?p=preview
You only need to add data in the right structure.
Have a look at the function
$("#btnAdd").click(function()
of my code script.js
I hope it helps.
regards,
Luis

ember model find query with params doesn't display on pagination

2I have an Ember app which connects to an api from where it gets articles. I make use of pagination to get 10 articles per request. This works. But now I wanted to add sorting to the request. I implemented this by using the extra parameter in the store.find.
However, for some reason if I use the 'return this.store.find('article', params);' instead of 'return this.store.find('article');' new articles (still requested and added correctly to the store!) in the getMore function are not beiing displayed or rendered. But when i remove the params parameter from store.find in model, it does work. What could be the case here?
templates/articles.hbs
<script type="text/x-handlebars" data-template-name="articles">
{{#each itemController="article"}}
<div class="item">
//...
</div>
{{/each}}
</script>
routes/articles.js
import Ember from 'ember';
export default Ember.Route.extend(Ember.UserApp.ProtectedRouteMixin, {
model: function(params) {
var params2 = {page: 1, per_page: 10, sort: params.sort};
return this.store.find('article', params2);
},
setupController: function(controller, model) {
controller.set('content', model);
},
actions:{
//...
},
getMore: function() {
// don't load new data if we already are
//if (this.get('loadingMore')) return;
//this.set('loadingMore', true);
var meta = this.store.metadataFor("article");
if (meta.hasmore) {
var controller = this.get('controller'),
nextPage = controller.get('page') + 1,
perPage = controller.get('perPage'),
sorting = controller.get('sort'),
items;
var params = {page: nextPage, per_page: perPage, sort: sorting};
this.store.findQuery('article', params).then(function (articles) {
controller.set('page', controller.get('page') + 1);
//this.set('loadingMore', false);
});
}
else{
$('#pagination_spinner').hide();
}
},
queryParamsDidChange: function() {
this.refresh();
}
}
});
controllers/articles.js
import Ember from 'ember';
var ArticlesController = Ember.ArrayController.extend({
itemController: 'article',
queryParams: ['sort'],
sort: 'rating',
page: 1,
perPage: 10
});
export default ArticlesController;
views/articles.js
import Ember from 'ember';
export default Ember.View.extend({
didInsertElement: function(){
//this.scheduleMasonry();
this.applyMasonry();
// we want to make sure 'this' inside `didScroll` refers
// to the IndexView, so we use jquery's `proxy` method to bind it
//this.applyMasonry();
$(window).on('scroll', $.proxy(this.didScroll, this));
},
willDestroyElement: function(){
this.destroyMasonry();
// have to use the same argument to `off` that we did to `on`
$(window).off('scroll', $.proxy(this.didScroll, this));
},
// this is called every time we scroll
didScroll: function(){
if (this.isScrolledToBottom()) {
$('#pagination_spinner').addClass('active');
this.get('controller').send('getMore');
}
},
scheduleMasonry: (function(){
Ember.run.scheduleOnce('afterRender', this, this.applyMasonry);
}).observes('controller.model.#each'), //TODO check
applyMasonry: function(){
$('#pagination_spinner').removeClass('active');
var $galleryContainer = $('#galleryContainer');
$galleryContainer.imagesLoaded(function() {
// check if masonry is initialized
var msnry = $galleryContainer.data('masonry');
if ( msnry ) {
msnry.reloadItems();
// disable transition
var transitionDuration = msnry.options.transitionDuration;
msnry.options.transitionDuration = 0;
msnry.layout();
// reset transition
msnry.options.transitionDuration = transitionDuration;
} else {
// init masonry
$galleryContainer.masonry({
itemSelector: '.item',
columnWidth: 0,
"isFitWidth": true
});
}
});
},
destroyMasonry: function(){
$('#galleryContainer').masonry('destroy');
},
// we check if we are at the bottom of the page
isScrolledToBottom: function(){
var distanceToViewportTop = (
$(document).height() - $(window).height());
var viewPortTop = $(document).scrollTop();
if (viewPortTop === 0) {
// if we are at the top of the page, don't do
// the infinite scroll thing
return false;
}
return (viewPortTop - distanceToViewportTop === 0);
}
});
nothing smart coming to my mind, but maybe it's that...
You've got the line:
if (meta.hasmore) {
in your getMore() function. Is this the case that you've got this meta field in one response and forgot in the other?

Jqplot pie chart rendering only lines

am loading jqplot corresponding files dynamically and passed data to the and chart div but at sometimes am getting the graph and some other time am not getting the graph my code as follows i maid an ajax call to get the values and passed to the graph in object st and the output am getting is shown here http://i43.tinypic.com/wcfns0.png please help me function
jsFunction3(xyz) {
jQuery.getCSS = function( url, media )
{
jQuery( document.createElement('link') ).attr({ href: url, media: media || 'screen', type: 'text/css', rel: 'stylesheet' }).appendTo('head'); };
$.getCSS('/redkanproject/plugins/jqplot-0.1/css/jqplot/jquery.jqplot.css','print');
$.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/jquery.jqplot.min.js',
function() { }); $.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/excanvas.min.js', function() { });
$.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/plugin/jqplot.pieRenderer.min.js', function() { });
var JSONObject = new Object;
JSONObject.id =xyz;
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'page', action:'example4')}"; new Ajax.Request(url, { method:'post', contentType:'application/json', postBody:JSONstring, asynchronous:true, onSuccess: function (res) {
st=(res.responseJSON)
x="chart" // this is my div to display chart
var plot1 = $.jqplot (x, [st], { title: 'Bianual Reviews percentage', grid: {
background:'#834100', shadow: true,borderWidth: 0, borderColor: 'white',shadowDepth: 0}, seriesDefaults: {
// Make this a pie chart.
renderer: $.jqplot.PieRenderer, rendererOptions: {
// Put datalabels on the pie slices.
// By default, labels show the percentage of the slice.
sliceMargin:6,
showDataLabels: true
}
},
legend: { show:true, location: 'e' } } );
$(x).bind('jqplotDataClick', function(ev,seriesIndex, pointIndex, data)
{ alert(" data: "+data); }
);
}
})//ajax }
------------------------------------------------------------------------
I had a similar issue and it turned out that I had a global style on the table element which sets the width to 100%.
eg
table{
width:100%
}
I changed that to auto and everything displayed correctly
table{
width:auto;
}
Hope that helps :-)

Sencha Touch Carousel From JSON Store

I'm building a Wordpress site using Sencha Touch. I've created a plugin that converts the posts to JSON for the application to read.
In the Applications "Post View" I am loading post information (Title, Body, etc) and I would like to have a carousel that displays all the images within the array "images" I've put through the json within the post.
My application is using the MVC structure (because I like the feeling of my teeth being pulled) and so I need a list of posts to pass the data through onto the Single Posts panel, then get the Images array into the carousel.
The goal is to select a post from the list, load the data into the postsingleview (currently working) and then load the images from that post into the carousel.
Any and all suggestions much appreciated.
Here's what I have so far:
JSON: http://pastie.org/2497239 (Stack's codewrapper wouldn't let me display json, here's the pastebin)
PostListView:
App.views.PostListView = Ext.extend(Ext.Panel, {
postStore: Ext.emptyFn,
postList: Ext.emptyFn,
id:'postlistview',
layout: 'card',
initComponent: function () {
this.postList = new Ext.List({
store: App.stores.postStore,
grouped: true,
emptyText: '<div style="margin:5px;">No notes cached.</div>',
onItemDisclosure: true,
indexBar: true,
itemTpl: '<div class="list-item-title">{title}</div>',
});
this.postList.on('disclose', function (record) {
this.onViewPost(record);
}, this),
this.items = [this.postList];
App.views.PostListView.superclass.initComponent.call(this);
},
onViewPost: function (record) {
Ext.dispatch({
controller: App.controllers.masterController,
action: 'viewpost',
record: record,
});
},
});
Master Controller with "ViewPost" action:
'viewpost': function (options) {
App.views.postSingleView.bodycard.update(options.record.data);
App.views.postSingleView.funfactcard.update(options.record.data);
App.views.postSingleView.crosscard.update(options.record.data);
App.views.postSingleView.historycard.update(options.record.data);
App.views.postSingleView.architectcard.update(options.record.data);
App.views.postSingleView.commentcard.update(options.record.data);
App.views.postSingleView.dealscard.update(options.record.data);
App.views.postView.setActiveItem(
App.views.postSingleView,
{ type: 'slide', direction: 'left' }
);
},
Post Single View (Which displays the data from the post)
App.views.PostSingleView = Ext.extend(Ext.Panel, {
title:'Single Post',
id:'postsingleview',
layout:{
type:'vbox',
align:'stretch',
pack:'end'
},
defaults: { flex: 1 },
initComponent: function () {
this.bodycard = new Ext.Component({
title:'Info',
scroll:'vertical',
cls : 'card bottomcard card3',
iconCls:'info',
tpl: '<tpl for=".">' +
'<div id="bottomcard-container">{body}</div>' +
'</tpl>',
});
[... There are 7 Ext.Components, but I want to keep it short so I'm deleting them for Display on Stack ]
this.postSinglePanel = new Ext.TabPanel({
dock:'bottom',
id:'singlepost-bottompanel',
items:[
this.bodycard,
this.funfactcard,
this.crosscard,
this.historycard,
this.architectcard,
this.commentcard,
this.dealscard,
],
tabBar:{
dock:'bottom',
scroll:'horizontal',
layout:{
pack:'center',
},
},
});
var numberOfPages = 4;
// Create pages for the carousel
var pages = [];
for (var i=0; i<numberOfPages; i++) {
pages.push(new Ext.Component({
id: 'page'+i,
cls: 'page',
tpl: '<tpl for=".">{body}</tpl>',
}));
}
// Create the carousel
this.carousel = new Ext.Carousel({
id: 'carousel',
defaults: {
cls: 'card'
},
items: pages,
});
this.items = [this.carousel, this.postSinglePanel];
App.views.PostSingleView.superclass.initComponent.call(this);
},
});
I think that this is what you need.
Basically the idea is to manually add the carousel items after the store has finished loading the data.
Here is a basic code for creating a carousel and populating the items from a store.
this specific example is for an image gallery:
myApp.views.ImageGallery = Ext.extend(Ext.Panel,{
layout: {
type: 'fit'
},
initComponent: function() {
this.setLoading(true,true);
var proxyUrl = 'my_url'
var store = new Ext.data.Store({
panel: this,
model: 'myModel',
proxy: {
type: 'ajax',
url: proxyUrl,
reader: {
type: 'json'
}
},
listeners: {
single: true,
datachanged: function(){
var items = [];
store.each(function(rec){
items.push({
html: '<img class="myImage" src=' + rec.get('imageUrl') + '>'
});
});
var carousel = new Ext.Carousel({
cardSwitchAnimation: 'slide',
layoutOnOrientationChange: true,
ui: 'light',
items: items,
style: 'background: #000',
itemId: 'carousel'
});
this.panel.setLoading(false);
this.panel.add(carousel);
this.panel.doLayout();
}
}
});
store.read();
myApp.views.ImageGallery.superclass.initComponent.call(this);
}});

Resources