Ajax call to get data to highchart - c#

I am trying to make a spline chart using highcharts that updates every second.
The data comes from the DB.
my script is :
<script>
$(function () {
var c = [];
var d = [];
$('#container').highcharts({
chart: {
type: 'spline',
events: {
load: getData
}
},
title: {
text: 'PUNCHING DETAILS'
},
xAxis: {
categories: c
},
yAxis: {
title: {
text: 'punching'
},
labels: {
formatter: function () {
return this.value ;
}
}
},
tooltip: {
crosshairs: true,
shared: true
},
series: [{
name: 'PUNCHING',
data: d
}]
});
});
function getData() {
alert("hi");
$.ajax({
url: "Default.aspx/GetData",
dataType: 'json',
success: function (data) {
console.log(data)
var categories = [];
var seriesData = [];
$.each(data, function (i, e) {
categories.push(i);
seriesData.push(parseInt(e));
});
chart.xAxis[0].setCategories(categories);
chart.series[0].setData(seriesData);
setTimeout(requestData, 1000);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
},
cache: false
});
}
</script>
And cs code is :
public partial class ajax_main_Testpages_Realtime_Graph_Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
public static string GetData()
{
String con1 = ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();
List<string> list_time = new List<string>();
List<int> list_count = new List<int>();
var serie_line_Dept = new { data = new List<object>() };
string query = #"select item_count,entered_time p_time from st_request where rownum<=10";
OdbcConnection connection = new OdbcConnection(con1);
connection.Open();
OdbcCommand cmdSelect = connection.CreateCommand();
cmdSelect.CommandText = query;
OdbcDataReader readerSelect = cmdSelect.ExecuteReader();
while (readerSelect.Read())
{
serie_line_Dept.data.Add(new List<object>() { readerSelect["p_time"].ToString(), int.Parse(readerSelect["item_count"].ToString()) });
list_time.Add(readerSelect["p_time"].ToString());
list_count.Add(int.Parse(readerSelect["item_count"].ToString()));
}
JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
return oSerializer1.Serialize(serie_line_Dept);
}
}
I get the this error: Unexpected token <.
No graph is displayed.
I referred here for the above code.
I am new to json and jquery, I am unable to solve this.
Can anyone please help me on this?
Thanks in advance.

Related

asp.net C# jQuery Tokenize2 suggestion not show

I try using jQuery tokenize2 with asp.net/C#, I try to get suggestions from ajax. When I try to inspect, firebug or visual studio, there is no error, but the tokenize2 not working.
here are the code:
Webservice:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetRelated(string search)
{
SearchEntity[] arrEnt = new SearchEntity[]
{
new SearchEntity()
{
Value = "value 1",
Text = "text 1"
},
new SearchEntity()
{
Value = "value 2",
Text = "text 2"
}
};
return JsonConvert.SerializeObject(arrEnt, Newtonsoft.Json.Formatting.Indented);
}
Javacript:
<script>
$(document).ready(function () {
$('.autoCom').tokenize2({
dataSource: function(term, object) {
$.ajax('GetData.asmx/GetRelated', {
data: { search: term, start: 0 },
dataType: 'json',
success: function(data) {
var $items = [];
$.each(data, function(k, v) {
$items.push(v);
});
object.trigger('tokenize:dropdown:fill', [$items]);
}
});
}
});
});
</script>
Please tell me, is there something wrong with the code?

get data from database using Json for search method

i have a issue , my problem is it i can't use my object form my model using EF , i need this method for a autocomplete search;
this is my error message :
"The System.NotSupportedException exception occurred HResult = 0x80131515 Message = The entity type or complex type 'PizzaTn.Context.ViewModels' cannot be built in a LINQ to Entities query. Source = Procedure call tree:
public JsonResult GetSearchValue(string search)
{
PizzaTnContext db = new PizzaTnContext();
List<VilleModels> allsearch = new List<VilleModels>();
allsearch = db.Villes.Where(x => x.VilleName.Contains(search)).Select(x => new VilleModels
{
IdVille = x.IdVille,
VilleName = x.VilleName
}).ToList();
return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
this my HTML
<script>
$("#searchInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetSearchValue", "Home")',
datatype: "json",
data: {
search: $("#searchInput").val()
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.VilleName, value: item.VilleName };
}
)
);
},
error: function (xhr, status, error) {
alert("error");
}
});
}
});
</script>
the solution is to add an argumant .AsEnumerable() .. thanks George:
db.Villes.Where(x => x.VilleName.Contains(search)).AsEnumerable().Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();

Highchart piechart cant get data from database c#

<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Blood Volume'
},
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] = $('<%=ddlLocation.ClientID%>').val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebForm1.aspx/getBloodInventory",
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.id, item.volume];
var obj = {};
obj.name = item.id;
obj.y = item.volume;
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>
[WebMethod]
public List<bloodInventory> getBloodInventory(List<string> pData)
{
List<bloodInventory> p = new List<bloodInventory>();
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection cn = new SqlConnection(conn))
{
string myQuery = "select blood_group_id,SUM(volume) as volume from BloodInventory b, Donors d where (b.donor_id = d.donor_id and blood_bank_id=#blood_bank_id)";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#blood_bank_id", pData[0]);
cmd.Connection = cn;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
bloodInventory cpData = new bloodInventory();
cpData.id = dr["blood_group_id"].ToString();
cpData.volume = Convert.ToInt32(dr["volume"].ToString());
p.Add(cpData);
}
}
}
return p;
}
Above is my code where i want to display a piechart based on selection from dropdown list. When i click the button to show it shows that error 404 which the url not found, can i know what is the problem?

google.visualiztion.ColumnChart() dont work

Here is my Jquery Ajax code to create a column chart using the Google API.
$(document).ready(function () {
//load Data Here
var chartData = null;
$.ajax({
url: '/Dashboard/GetData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
google.charts.load("current", { packages: ['corechart'] });
drawChart(chartData);
}).fail(function () {
alert("Sorry. Server unavailable. ");
});
});`
function drawChart(d) {
var charData = d;
var data = null;
data = google.visualization.arrayToDataTable(charData);
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; }
}, {
type: 'number',
label: data.getColumnLabel(3),
calc: function () { return 0; }
}
]);
var options = {
title: 'Bodily Analysis',
legend: 'bottom',
hAxis: {
title: 'Year',
format: '#'
},
vAxis: {
minValue: 0,
maxValue: 1000,
title: 'Measurements'
},
chartArea: {
left: 100,
top: 50,
width: '70%',
height: '50%'
},
animation: {
duration: 1000
}
};
alert(data);
var chart = new google.visualiztion.ColumnChart(document.getElementById('visualization'));
alert(data);
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
And here is my MVC controller which return data from the database in form of JSON.
public JsonResult GetData()
{
List<BusinessContact> Bc = new List<BusinessContact>();
using (BusinessContContext db = new BusinessContContext())
{
Bc = db.BusinessContacts.OrderBy(a => a.birthDate).ToList();
}
var charData = new object[Bc.Count + 1];
charData[0] = new object[]
{
"Birth",
"height",
"ChestMeasurement",
"Weight"
};
int j = 0;
foreach (var i in Bc)
{
j++;
charData[j] = new object[]
{
Convert.ToDateTime(i.birthDate).Year,
Convert.ToUInt32(i.height),
Convert.ToUInt32(i.ChestMeasurement),
Convert.ToUInt32(i.Weight)
};
}
return new JsonResult{Data = charData, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
The problem I have is that the chart does not render after the JsonResult is gotten from database. I noticed that alert is not prompted right after the
var chart = new google.visualiztion.ColumnChart(document.getElementById('visualization'));
Please i need help with this.

How can I return JSON via C# and parse it in JavaScript?

I am using a web service that gets data from my active directory and returns an array of objects to my javascript. The problem is the I am the response encapsulated in Object with _type included when I just want to return the value of the object like this
([{ value: "one", label: "Foo" }, { value: "two", label: "Bar" }]).
But I am receiving this
[Object { __type="Service+NameDTO", value: "one", label: "Foo"}, Object { __type="Service+NameDTO", value: "two", label: "Bar"}]
Here is my c#
public NameDTO[] GetCompletionList(string prefix)
{
var nameList = new List<NameDTO>();
DirectorySearcher search = new DirectorySearcher();
string strPath = search.SearchRoot.Path;
DirectoryEntry entry = new DirectoryEntry(strPath);
search.PageSize = 1000;
search.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=*" + prefix + "*))";
foreach (SearchResult sResultSet in search.FindAll())
{
if (sResultSet.Properties["mail"].Count > 0)
{
var dto = new NameDTO()
{
label = (string)sResultSet.Properties["displayName"][0],
value = (string)sResultSet.Properties["mail"][0],
};
nameList.Add(dto);
}
}
NameDTO[] myArray = nameList.ToArray();
return myArray;
}
public class NameDTO
{
public string label { get; set; }
public string value { get; set; }
}
and my javascript
<script type="text/javascript">
$(document).ready(function () {
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
$.ajax({
url: '<%#ResolveUrl("~/Service1.asmx/GetCompletionList") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return data
}))
},
success: function(response) {
$.each(response, function(key, val) {
alert(val.id);
});
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
search: function () {
var term = this.value;
if (term.length < 3) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
},
});
});
</script>
You probably need some typical JSON builder.
Server-side, you can make dictionaries, arrays, etc and throw everything into a
JsonMapper.ToJson(jsonDict)
call.
This function in my project indirectly calls JsonSerializer(), the Newtonsoft JSON handler. Very useful for both serializing and deserializing the JSON.
I may be misinterpreting your question, though; a bit vague.
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx is pretty darn relevant here, and very useful.
It came up that you might need this:
var jsonString = #Model; //or however you get your string.
var json = JSON.parse(jsonString);

Categories

Resources