Highcharts with ajax and json data what am i doing wrong? - asp.net

I have been trying for days to plot a simple line graph utilising HighchartsJS via ajax. I have tried posting on their forum but help seem to be slow in coming forward.
I am using ASP.NET web forms.
Server Side
<WebMethod(EnableSession:=True)> _
Public Function getData() As String
Dim dr As DataRepository = New DataRepository
Dim data As List(Of ArrayList) = New List(Of ArrayList)
For Each q In dr.getAllData()
Dim a As New ArrayList
Dim d As Date = q.DateTime
a.Add(d.Ticks)
a.Add(q.TotalRevenue)
data.Add(a)
Next
Dim ser As Serie = New Serie(data)
Dim str As String = JsonConvert.SerializeObject(ser)
Return str
End Function
This returns the following json object, Please note the double quotes wrapping everything.
"{"data":
[
[634420512000000000,100000.0000],
[634421376000000000,100086.0000],
[634422240000000000,100171.0000],
[634423104000000000,100257.0000]
]
}"
Clientside i am calling the above function and rendering my chart like so.
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {},
xAxis: {
type: 'datetime'
},
yAxis: {},
series: []
};
$.ajax({
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
url: "_services/ScriptService.asmx/getData",
success: function (items) {
var obj = jsonParse(items.d);
var series = { data: [] };
$.each(obj, function (itemNo, item) {
series.data.push(item);
});
options.series.push(series);
},
cache: false,
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); }
});
chart = new Highcharts.Chart(options);
});
'items' in the above call is as follows;
"{"data":
[
[634420512000000000,100000.0000],
[634421376000000000,100086.0000],
[634422240000000000,100171.0000],
[634423104000000000,100257.0000]
]
}"
I use 'jsonParser(items.d') to create a correct json object(removing the double quotes).
'obj' now contains my json object and 'item' when inspected in firebug now looks like this;
[
[634420512000000000, 100000],
[634421376000000000, 100086],
[634422240000000000, 100171],
[634423104000000000, 100257]
]
When my chart renders, the points do not get plotted. What am I doing wrong?
Solved the issue.
Needed to change the line
series.data.push(obj.data);
to;
series.data = obj.data;

Put chart = new Highcharts.Chart(options); inside success event.

Solved the issue.
Needed to change the line
series.data.push(obj.data);
to;
series.data = obj.data;

Related

jqueryui autocomplete with json does nothing

BLUF: I have jqueryui autocomplete wired into an AJAX-y JSON-y DB lookup. It calls the page correct, and the page returns JSON. However, it doesn't actually load those results into the UI. It appears to very slowly do nothing.
Relevant JS:
$(function () {
$("#searchtext").autocomplete({
source: function (request, response) {
$.getJSON("<%=ResolveUrl("~/getPeople?prefix=") %>" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
select: function (e, i) {
$("#personID").val(i.item.val);
},
minLength: 2,
delay: 100
});
});
Code of getPeople.aspx:
Response.Headers.Add("Content-type", "text/json")
Response.Headers.Add("Content-type", "application/json")
Dim prefix
prefix = Request.QueryString("prefix")
Dim PDU_CS = System.Configuration.ConfigurationManager.ConnectionStrings("PDU").ConnectionString
Using PDU_Connection As New System.Data.SqlClient.SqlConnection()
PDU_Connection.ConnectionString = ConfigurationManager.ConnectionStrings("PDU").ConnectionString
Using PDU_Command As New System.Data.SqlClient.SqlCommand()
PDU_Command.CommandText = "select id, [name] FROM vw_Staff WHERE [name] LIKE #searchtext + '%'"
PDU_Command.Parameters.AddWithValue("#searchtext", prefix)
PDU_Command.Connection = PDU_Connection
PDU_Connection.Open()
Using sdr As System.Data.SqlClient.SqlDataReader = PDU_Command.ExecuteReader()
Dim dt As New DataTable
dt.Load(sdr)
Dim sData As String = JsonConvert.SerializeObject(dt)
Response.Write(sData)
End Using
PDU_Connection.Close()
End Using
End Using
Actual output from getPeople.aspx?prefix=Gibson
[{"id":5854,"name":"GIBSON, NICHOLAS"}]
Would suggest two changes:
$(function() {
$("#searchtext").autocomplete({
source: function(request, response) {
$.getJSON("<%=ResolveUrl("~/getPeople?prefix=") %>" + request.term, function (data) {
response($.map(data.dealers, function(value, key) {
return {
label: value.name,
value: value.id
};
}));
});
},
select: function(e, i) {
$("#personID").val(i.item.value);
return false;
},
minLength: 2,
delay: 100
});
});
Since you're passing an Array of Object to $.map(), you need interact with each Object, in this case the value of the array.
select has ui, in your case, just i, and it is i.item.value, not i.item.val.
Reference: https://jqueryui.com/autocomplete/#custom-data

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>

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

jqgrid form editing editoptions select ajax add parameter

i'm trying to build a select element in the form editing jqgrid by calling an ajax webmethod (asp.net).
Everythings work great if I call a method without parameter. It doesn't work if I try to call a webmethod expecting a string parameter:
this is an extract of the code:
ajaxSelectOptions: { type: "POST", contentType: 'application/json; charset=utf-8', },
colNames: ['City', 'State'],
colModel: [
{
name: 'City',
index: 'City',
align: "center",
width: 80,
searchoptions: { sopt: ['eq', 'ne', 'cn']} ,
edittype: 'select',
editable: true,
editrules: { required: true },
editoptions: {
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceGeographic.asmx/GetCityByState") %>',
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
var s = '<select id="customer_City" name="customer_City">';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
s += '<option value="' + response[i]["Id"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return s + "</select>";
}
}
},
...
where can i set the parameter to send to the GetCityByState webmethod?
EDIT: I did not highlight that I'm using POST to call webmethod. Even if i tried as Oleg suggested on this link, it doesn't work :(
I think you need ajaxSelectOptions parameter of jqGrid. For example if you need to have the id of the selected row as an additional id parameter sent to webmethod identified by dataUrl you can use data parameter of ajaxSelectOptions in function form:
ajaxSelectOptions: {
type: "GET", // one need allows GET in the webmethod (UseHttpGet = true)
contentType: 'application/json; charset=utf-8',
dataType: "json",
cache: false,
data: {
id: function () {
return JSON.stringify($("#list").jqGrid('getGridParam', 'selrow'));
}
}
}
because in the code above the parameter dataType: "json" are used you should modify the first line of buildSelect from
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
...
to
buildSelect: function (data) {
var response = $.parseJSON(data.d);
...
Moreover because you use the line $.parseJSON(data.d) I can suppose that you return the data from the webmethod in the wrong way. Typically the type of return value from the webmethod should be class. You should don't include any call of manual serialization of the returned object. Instead of that some people misunderstand that and declare string as the return type of the webmethod. They makes JSON serialization manually with call of DataContractJsonSerializer or JavaScriptSerializer. As the result the manual serialized data returned as string will be one more time serialized. It's the reason why you can have two calls of $.parseJSON: var retValue = $.parseJSON(data); var response = $.parseJSON(retValue.d);. If you will be use dataType: "json" inside of ajaxSelectOptions and if you would do no manual serialization to JSON in web method and just rejurn the object like it be, you would need to have no call of $.parseJSON at all. You can just use directly data.d:
buildSelect: function (data) {
var response = data.d;
...

JQuery Ajax with multiple return values from ASP.NET

How can I return multiple values from JQuery.Ajax() in the success function ?
I tried it:
$.ajax({
type: "POST",
url: "default.aspx/myFunction",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#myDiv").html(msg.a[0]);
$("#myDiv2").html(msg.a[1]);
}
});
And here my ASP.NET page:
<WebMethod()> _
Public Shared Function myFunction() As Array
Dim a() As String
a(0) = "value 1"
a(1) = "value 2"
Return a
End Function
It works just in unique return string, but array doesn't work :(
Change it to msg.d[0].
Wirting msg.a is completely wrong; the method's return value has nothing to do with a variable name.
However, for security reasons, ASP.Net wraps the JSON object in a d property, so you need to write msg.d to access the array.
For Myself I used response.d to return the full array formatted in Comma's ex.[1,2,3]. To receive an individual, it's the same as the above (response.d[0]). The values were returned to AJAX as List(Of Strings) using a WebMethod.
var Str = {};
Str.StrVal = 'Test1';
Str.StrVal2 = 'Test2';
Str.StrVal3 = 'Test3';
Str.StrVal4 = 'Test4';
$.ajax({
type: "POST",
url: "VB.aspx/GetString",
data: '{Str: ' + JSON.stringify(Str) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully." + response.d);
//window.location.reload();
//window.data("kendoWindow").close();
Str.StrVal = response.d[0]//response.d
//AddTab(response.d)
GetTabs(Str.StrVal)
},
error: function (response) {
alert(response.d)
}
});
Here is the Web Method, Sorry for the brief Variable Description's. Just a sample.
<WebMethod()> _
<ScriptMethod()> _
Public Shared Function GetString(Str As SendString) As List(Of String)
Dim a As New List(Of String)
a.Add("1")
a.Add("2")
Return a
End Function
Thanks
I got the solution!
I just use msg.d[0] instead msg.a[0]

Resources