Conversion of eloquent result to use with c3.js - laravel-blade

I need to generate a pie chart whose output will be a representation of eloquent output.
My query is:
$data = MyModel::select('province_id', DB::raw('COUNT(id) AS cnt'))
->groupBy('province_id')
->get();
dd($data) gives me:
Then it is passed to blade view as:
return view('tool.charts', ['data' => $data]);
In my blade view (js code is embedded in <script> tag):
var datax = {!! json_encode($data) !!};
var chart = c3.generate({
bindto: '#pie1',
data: {
columns: datax,
type : 'pie',
}
});
But this doesn't draw the pie chart. If I use hardcoded values, like:
var chart = c3.generate({
bindto: '#pie2',
data: {
columns: [
['data1', 30],['data2', 140],['data3', 40],['data4', 170],
],
type : 'pie',
}
});
It shows the chart as expected.
UPDATE:
column was changed to json and still has no luck.
var chart = c3.generate({
bindto: '#pie1',
data: {
json: datax,
type : 'pie',
}
});

First of all, pie chart is a bit different comparing to others (check here similar question).
For your case, I would suggest this:
In your controller, get data as json
public function myjson(Request $request){
$data = MyModel::selectRaw('province_id, COUNT(*) AS cnt')
->groupBy('province_id')
->get();
return response()->json($data->toArray());
}
define a route to access on this controller. Add this to your route:
Route::get('my/json', ['as'=> 'my.json', 'uses'
=>’MyController#myjson']);
Then define your chart inside a blade using AJAX (Not passing variable from controller like you did)
<script language="JavaScript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: '{{route('my.json')}}',
data: "{}",
contentType: "application/json",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result);
},
error: function (xhr, status, error) {
alert(error);
}
});
});
function OnSuccess(response) {
var data = {};
var lists = [];
response.forEach(function (e) {
lists.push(e.province_id);
data[e.province_id] = e.cnt;
});
var chart1 = c3.generate({
bindto: '#pie1',
data: {
json: [data],
type : 'pie',
keys: {
value: lists
}
}
});
};
</script>

Related

Draw chart.js with data from server

I know I must be doing a basic mistake but I am new to this. I would like to populate a line chart (chart.js) in my View with data from the server. I have confirmed that the data is received in the View but I suspect that it is in a wrong format.
My Controller:
public ActionResult GetLineChartData()
{
var data = new
{
title = "test_data",
data = new[] {
new { value = "V1", key = "11"},
new{ value = "V2", key = "10"}
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
On my View:
<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
$("#lineChartUpdate").click(function () {
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
data: {},
dataType: "json",
traditional: true,
success: function (data) {
new Chart('lineChart', {
type: 'line',
data: {
labels: data.data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
}
});
}
});
});
});
</script>
I am getting this error: "Invalid scale configuration for scale: yAxes"
This is because it is invalid as the errors says, you are using V2 config with V3.
In V3 all scales are there own object in the scales object instead of 2 arrays.
Changing to:
scales: {
y: {
// Scale config
}
}
Will remove the warning and make the config apply correctly
For all changes between V2 and V3 please read the migration guide

Google Charts Category Filter using SQL Server

I'm trying to create a dropdown filter that will allow filtering of chart(s). My webmethod is working (I've tested it using a chart) but my ajax is not returning any rows within the dropdown.
Any help really appreciated
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawCountryChart);
google.setOnLoadCallback(drawDivisionChart);
var dashboard = new google.visualization.Dashboard(
document.getElementById('Dashboard'));
function drawCountryChart() {
$.ajax({
type: "POST",
url: "Season.aspx/GetCountry",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var CountryData = google.visualization.arrayToDataTable(r.d);
var namePicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'ddlCountry',
'options': {
'filterColumnLabel': 'CountryName',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
}
if you just want to draw the filter on its own,
need to assign the data table property and call the draw method...
var CountryData = google.visualization.arrayToDataTable(r.d);
var namePicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'ddlCountry',
'dataTable': CountryData, // <-- assign data table
'options': {
'filterColumnLabel': 'CountryName',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
namePicker.draw(); // <-- draw control
note: recommend not using the older chart library --> jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only affect the load and callback statements,
in fact, the callback can be added to the load statement directly...
google.charts.load('current', {
callback: function () {
drawCountryChart();
drawDivisionChart();
},
packages:['corechart', 'controls']
});

Multiple Google Charts on Same Page from same Data using Entity model

I'm trying to setup a Web Page using the same data that is being pulled for the first chart. Data is being pulled by an edmx entity model. The code below works for single graph. I want to add a Pie Chart on the same page as well using the same data. All the examples I've seen are for graphs using static data. My code is below, I know I would need to just reproduce what I have in some fashion. Thanks,
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
#section Scripts{
<script>
$(document).ready(function () {
//Load Data Here
var chartData = null;
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
drawChart(chartData);
});
});
function drawChart(d) {
var chartData = d;
var data = null;
data = google.visualization.arrayToDataTable(chartData);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(0),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function () { return 0; }
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('visualization1'));
var options = {
}
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<div id="visualization1" style="width:900px; height:500px"></div>
}
first, recommend using...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not...
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
note: the load statement will be the only difference, as seen below...
next, you can draw as many charts as necessary,
after the load statement has completed
you must set a callback to know for sure,
that google charts has loaded all of the requested packages...
multiple packages can be loaded at the same time
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
the callback will also wait for the document to finish loading...
as such, $(document).ready isn't needed
recommend setup similar to following...
<script src="https://www.gstatic.com/charts/loader.js"></script>
#section Scripts{
<script>
function loadData() {
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
}).done(function (jsonData) {
drawCharts(jsonData);
});
}
function drawCharts(jsonData) {
var chartData = google.visualization.arrayToDataTable(jsonData);
var chartCol = new google.visualization.ColumnChart(document.getElementById('visualization-col'));
chartCol.draw(chartData);
var chartPie = new google.visualization.PieChart(document.getElementById('visualization-pie'));
chartPie.draw(chartData);
var chartTable = new google.visualization.Table(document.getElementById('visualization-table'));
chartTable.draw(chartData);
}
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
</script>
<div id="visualization-col"></div>
<div id="visualization-pie"></div>
<div id="visualization-table"></div>
}
note: each chart has a specific data format
although most of the charts in 'corechart' will be fine,
not all charts may work with the same data table...

Unable to get correct posted data from AJAX call in asp.net handler

I am calling a handler through a AJAX call .
code
var PostData = {"MyName": myName };
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: JSON.stringify(PostData),
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Inside ProcessRequest ,these values i am getting :
context.Request.Form.Count = 1
context.Request.Form[0] = "{'MyName':'dave'}"
context.Request.Form["MyName"] = null
How can get the posted data as :
context.Request.Form["MyName"] = "dave"
Thanks in advance :)
You need to send the data in the format of the post as:
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: 'MyName=dave&MoreData=SecondName',
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Also take a look at the encodeURIComponent, you may need to encode the parameters :
Combining two Javascript and jQuery scripts

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources