Draw chart.js with data from server - asp.net

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

Related

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

Conversion of eloquent result to use with c3.js

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>

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

Kendo AutoComplete Empty Filter in Querystring - serverfiltering

I'm trying to use serverfiltering for autocomplete in Kendo UI (ASP.NET 5, MVC6)
Due to fact that Autocomplete isn't available in MVC Wrapper, i had to use the code below:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET"
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
</script>
The problem is that querystring send to controller looks like this :
?sort=&group=&filter=
So it doesn't include any filter information
On serverside im trying to map it to DataSourceRequest
Right now im using following workaround to pass additional parameter to do serversidefiltering but still i'd like to use kendo native filtering for this:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET",
data: onAdditionalData
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
function onAdditionalData() {
return {
text: $("##Model.Name").val()
};
}
</script>
Controller code:
[Route("api/Get")]
[HttpGet]
public JsonResult Get([DataSourceRequest] DataSourceRequest request, string text = "")
{
var list = (new List<string>() { "value1", "value2", "value3", "test" } ).AsQueryable();
return Json(list.Where(x => x.Contains(text)).ToDataSourceResult(request));
}

why is my jqGrid is empty eventhough json data is present

Here is my jqGrid, that is not displaying any data.
I'm getting the json response for the grid, but it is not displaying.
Here is what i've done so far.
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
function getCompanyData() {
//debugger;
$.ajax({
url: "jqGrid_pureJS.aspx/GetCompanyList",
data: "{}", // "{}" For empty input data use "{}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//debugger;
var grdData = $("#jqGrid")[0];
grdData.addJSONData(result.d);
},
error: function (result) {
//debugger;
}
});
}
$(function () {
$("#jqGrid").jqGrid({
datatype: getCompanyData,
colNames: ['Id', 'Name', 'Address', 'City', 'Phone'],
colModel: [
{ name: 'F1', index: 'invid', width: 55 },
{ name: 'F2', index: 'invdate', width: 90,editable:true },
{ name: 'F3', index: 'amount', width: 80,editable:true, align: 'right' },
{ name: 'F4', index: 'tax', width: 80,editable:true, align: 'right' },
{ name: 'F5', index: 'total', width: 80,editable:true, align: 'right' }
],
pager: $("#pager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: 'My first grid',
width:800
}).navGrid('#pager', { edit:true,view: true, del: false });
});
</script>
And here is my webmethod that posts data.
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=false)]
public static string GetCompanyList()
{
var data = GetAllData();
try
{
string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return response;
}
catch (Exception ex)
{
return ex.Message;
}
}
And here is my json responce captured:
{"d":"
[\r\n
{\r\n
\"F1\": 1.0,\r\n
\"F2\": \"Name\",\r\n
\"F3\": \"Address\",\r\n
\"F4\": \"City\",\r\n
\"F5\": \"Phone\"\r\n
},
\r\n
{\r\n
\"F1\": 10.0,\r\n
\"F2\": \"abc\",\r\n
\"F3\": \"def\",\r\n
\"F4\": \"asd\",\r\n
\"F5\": \"998907\"\r\n
}
]
}
I could see similar question jqgrid not showing data, i've checked it and i did not get rid of my problem though
Why is the json data not appended ? How do i do it ?
Edit
as part of the answer, i've removed my javascript to call the jqGrid and replaced the code for it as posted in the answer by oleg.
Also i've made little changes to the code in the server side.
Here is what the server side code is:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string GetCompanyList()
{
var data = GetAllData();
//string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return data;
}
public static string GetAllData()
{
try
{
//Grab the connection string defined in web.config
var connectionString = ConfigurationManager.ConnectionStrings["Test_3ConnectionString"].ConnectionString;
DataTable dt = null;
//Command Text
string commandText = "SELECT * FROM EmpDetails";
dt = SQLHelper.ExecuteDataTable(connectionString, CommandType.Text, commandText, "EmpDetails");
string result = JsonConvert.SerializeObject(dt);
return result;
}
catch (Exception ex)
{
throw;
}
}
Things going weird hour by hour. When i run my application i've the following grid.
I only have 9 rows in my table and it is displaying viewing 1-10 of 552.
Can someone please help me what is wrong with the serialization
There are may errors in your code. It looks like you used some retro code example which is at least 3 years old.
The main error in the server code is usage of JsonConvert.SerializeObject inside of web method. If you defines ResponseFormat=ResponseFormat.Json then the method should return object of any type and not string. .Net convert the object automatically to JSON. So the type of return value of GetCompanyList() should be the same as the return type of GetAllData(). After the changes the web method should returns the data like
{
"d": [
{
"F1": 1,
"F2": "Name",
"F3": "Address",
"F4": "City",
"F5": "Phone"
},
{
"F1": 10,
"F2": "abc",
"F3": "def",
"F4": "asd",
"F5": "998907"
}
]
}
The second problem that you use datatype defined as function. It's low-level way which you should never use if you can get the data with respect jQuery.ajax with some parameters. jqGrid provide a lot of different customization way to change parameters of jQuery.ajax used by jqGrid internally. Typically it's enough to specify the options like
url: "jqGrid_pureJS.aspx/GetCompanyList",
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.d; }
},
gridview: true,
height: "auto",
loadonce: true
It's important additionally to remove all index properties from colModel. The usage of index other as name follows to errors if you use loadonce: true option.
If F1 column contains unique values then I recommend you to add key: true property to the definition of the column "F1".
The results of the changes should be like on the demo:

Resources