Using chart.js with laravel passing data from controller to view - javascript

Trying to utilize chart.js in my laravel app. In my controller, I'm using Eloquent to perform a simple query of the database:
//sampleController.php
public function test()
{
$inventories = Inventory::all();
$dates = $inventories->lists('updated_at');
$totals = $inventories->lists('item_4801');
return view('pages.test')
->with('dates')
->with('totals');
}
I'm passing 'dates' and 'totals' to my view:
//test.blade.php
#extends('app')
#section('content')
<canvas id="myChart" width="400" height="400"></canvas>
#stop
#section('footer')
<script src="assets/admin/js/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: {!! json_encode($dates) !!},
datasets: [
{
label: "My Data",
data: {!! json_encode($totals) !!}
}
]
};
var myLineChart = new Chart(ctx).Line(data);
</script>
#stop
This doesn't work. The chart placeholder shows but it seems the data is being read as null. I'm guessing I'm just not passing the data in the correct format, but not sure exactly how I would do that. I can confirm that the data is being passed from controller to view, as I can dump the variable and see the data. Evidently it's just not in a format that chartjs can understand.
Any information would be greatly appreciated. Just a nudge in the right direction would help.
Many thanks,
Clay

Turns out, it was the 'dates' variable causing the problem (in addition to a syntax error). Chartjs was looking for an array like:
["2015/06/08", 2015/06/13", "2015/6/20"]
instead of the collection object from the eloquent query.
So I ran $dates = array_column($inventories->toArray(), 'updated_at'); to get the array, then reformatted the dates by running:
foreach ($dates as $date){
$formatted_dates[] = date('m/d/Y', strtotime($date));
}
Then I passed $formatted_dates to the view.
I'm sure there's a better way, but I'm learning more everyday and it works for me!

In your model;
use this
public function getCreatedAtAttribute($value)
{
return date('m/d/Y', strtotime($value));
}

Related

Laravel- farhanwazir laravelgooglemaps

I am trying to add a google maps view but it doesn't seem to recognise where I want it to show. This is my current output.. just showing what appears to be the sea?
//route
Route::get('googlemap', 'MapController#map');
//controller
public function map() {
$config['center'] = 'Sydney Airport,Sydney';
$config['zoom'] = '14';
$config['map_height'] = '400px';
$gmap = new GMaps();
$gmap->initialize($config);
$map = $gmap->create_map();
return view('map',compact('map')); }
//view
<html>
<head>
<title>Laravel Google Maps Example</title>
{!! $map['js'] !!}
</head>
<body>
<div class="container">
{!! $map['html'] !!}
</div></body></html>
I have my config file set up and I have added my google API key..
Any idea why this is happening?
Use the latitude and longitude values instead of the name of the location. e.g to center the map to Kampala, Uganda I used this
$config['center'] = '0.347596, 32.582520';
It is probably too late but I will tell you my solution in case another needs it.
The solution was to add the key in a certain line of code in the GMaps.php file:
This is how it was at the beginning:
$data_location = "https://maps.google.com/maps/api/geocode/json?address=".urlencode(utf8_encode($address))."&sensor=".$this->sensor;
This is how it has to be:
$data_location = "https://maps.google.com/maps/api/geocode/json?address=".urlencode(utf8_encode($address))."&sensor=".$this->sensor."&key=".$this->apiKey;

Locale language for google charts not working

In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};

Unable to Get TaffyDB Working

Trying to use TaffyDB in an AngularJS project, but i'm unable to get Taffy working.
Every time i try to get data from the TaffyDB, it's empty:
Object {extend: undefined, insert: undefined}
I'm just tying to do a simple test from their website:
<script src="vendors/taffydb-master/taffy.js"></script>
<script>
$(document).ready(function () {
//TaffyDB
var friends = TAFFY([
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
]);
console.log(friends());
});
</script>
What am i doing wrong?
Change
console.log(friends());
instead do
console.log(friends().get());

How to properly pass json to a view

I have a view with some javascript code for a pie chart in it. This view has an action method, where I am running some queries an converting the results to json in order to fill the pie chart with something.
The problem is that I don't know (and couldn't understand from another questions here) how to properly return a json from action to view and actually work with the data in some way in the view.
Currently, what I have give me a json string in my browser instead of a view.
I do not have a model in my project for the data that's in in the json.
Here's all the code from my view :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['German', 5.85],
['French', 1.66],
['Italian', 0.316],
['Romansh', 0.0791]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: 'Accumulated experience',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div id="piechart" style="width: 1000px; height: 600px;"></div>
And here is my controller :
public ActionResult experiencePieChart()
{
//some queries
var json = JsonConvert.SerializeObject(perclist);
return Json(json, JsonRequestBehavior.AllowGet);
}
your controller method should return JsonResult, just change it's signature in following way:
public JsonResult experiencePieChart()
{
var perclist = ...
//some queries
return Json(perclist, JsonRequestBehavior.AllowGet);
}
then in your js code you could call it
$(document).ready(function()
{
$.get("/YourController/experiencePieChart",ShowPieChart,"json").fail(ShowPieChartFail);
});
of course then you need define ShowPieChart function which will render that graph
function ShowPieChart(chartData){
// this code will be executed after result is returned asynchronously
// chartData contains JSON representation of perclist variable
}
In case you'd like to do that data-transfer just on each refresh of page, you could store data required for chart. In your .cshtml you'd just add
<script type="text/javascript">
var ChartData = #Html.Raw(Json.Encode(#Model.MyData))
</script>
then during execution of js on client side you'd have ChartData variable initialized. Anyway this way have multiple downside and is not scalable at all. Going with ajax call seems much better to me.

create Google Chart through AJAX call with JSON/JS

CI'm having an issue creating a chart. I've read number of tutorials and basically wrote a code according to them. However, the problem is that the chart won't be displayed at all.
I want on AJAX call to retrieve data from SQLite3 and then draw a chart based on that data.
It could be Column or Pie chart, doesnt matter.
I'm pretty sure there is some kind of problem with the way I work on JSON, and I would like someone to help me. Thanks!
#test.html
-------------------------------------------------------------------------
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "test-return.php",
dataType: "json",
async: false
}).responseText;
document.getElementById('rightDiv').innerHTML = jsonData;
var jsonData2 = [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19],["US Citt\u00e0 di Palermo",18],["SSC Napoli ",15],["Juventus FC ",16],["Parma FC ",14],["Genoa CFC ",14],["AS Bari ",13],["AC Fiorentina ",13],["SS Lazio ",11],["Calcio Catania ",10],["Cagliari Calcio ",11],["Udinese Calcio ",11],["AC Chievo Verona ",12],["Bologna FC ",10],["Atalanta BC ",9],["AC Siena ",7],["AS Livorno Calcio ",7]];
var data = google.visualization.arrayToDataTable(jsonData2,true);
var options = {
title: 'table 1'
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 500px;"></div>
<div id="rightDiv">query results</div>
</body>
</html>
#test-return.php
-----------------------------------------------------------------------------
<?php
sqlite code here
................
echo json_encode($row_array);
?>
$row_array output => [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19]......
You have to match your data format to format expected by your chosen chart type. As-is, you will have 3 columns of data: one numeric, one string, and one numeric. The PieChart expects two columns of data: the first should be type "string" and the second should be type "number". ColumnCharts can have any number of columns: the first can be either type "number", "date", "datetime", "timeofday", or "string", but all of the following columns should be type "number" (usually, that is - there are some exceptions that have to do with using column roles which are outside the scope of what you are doing here).
Looking at your data, I am speculating that the first column (the 1, 2, 3, 4... in your sample data) is a row number and not something you intend to plot. If this is the case, you need to adjust your server-side code to remove it. If this is not the case, can you provide information about it so I can help you figure out how to use it?
Also, your data is missing column headers. As structured, the arrayToDataTable method will take the first row of data and use it as the column headers, so you would get three columns with the labels "1", "FC Internazionale ", and "24", which you probably don't want. Either amend your server-side code to make the first row of data contain column labels, or set the second argument in the arrayToDataTable call to true.
By using jsonData = $.ajax(...).responseText;, you are bypassing the JSON conversion that jQuery does and passing the raw text of the response to jsonData. Since you need a javascript array to use the arrayToDataTable method, you need to call JSON.parse on jsonData to convert it to an array:
var data = google.visualization.arrayToDataTable(JSON.parse(jsonData), true);

Categories

Resources