Highchart piechart cant get data from database c# - 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?

Related

asp.net google charts problems my project

this code does not work. what should i do please help me there is no problem in database i couldn't find the solution
Is there a problem with WebMethod? I did everything but there is something I can't see
I'm stuck on this, my project is waiting for this
I will be very grateful to the friend who solved this
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<ChartDetails> GetPiechartData()
{
List<ChartDetails> dataList = new List<ChartDetails>();
string sConnString = "Data Source=.;Initial Catalog=deneme;Integrated Security=True";
SqlConnection baglanti = new SqlConnection(sConnString);
SqlCommand cmd = new SqlCommand("select begeni , kontrolid from yorum", baglanti);
baglanti.Open();
SqlDataReader droku = cmd.ExecuteReader();
while (droku.Read())
{
dataList.Add(new ChartDetails
{
kontrolid = droku["kontrolid"].ToString(),
begeni = Convert.ToInt32(droku["begeni"]),
});
}
return dataList;
}
public class ChartDetails
{
public string kontrolid { get; set; }
public int begeni { get; set; }
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
</script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default17.aspx/GetPiechartData",
data: "{}",
success: function (response) {
drawchart(response.d);
},
error: function () {
alert("Error loading data...........");
}
});
})
function drawchart(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'kontrolid');
data.addColumn('number', 'begeni');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].kontrolid, dataValues[i].begeni]);
}
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
}
</script>

How Use Select 2 and Json to display a big DataSet

I have a problem displaying the data in the dropdown list using select2. I think the reason is the Query returning many rows. when I limit the number of Row to 50 (where Rownum <=100 ) the data displayed but when I remove the where condition no data display. The PatientDemo table has more than 600000 rows Any help how to solve this issue. I am using Orcale and C#
View
<link href="~/Content/css/select2.min.css" rel="stylesheet" />
<div class="jumbotron">
<input type="hidden" id="textBoxVal" />
<select class="mySelect2" style="width:500px;">
</select>
</div>
<script>
$(document).ready(function () {
$(".mySelect2").select2({
placeholder: "Select category",
allowClear: true,
theme: "classic",
ajax: {
url: "/Home/GetCategory",
dataType: 'json',
delay: 10000,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data, params) {
return {
results: data
};
}
}
});
});
$(".mySelect2").on("change", function () {
var catId = $(this).val();
$("#textBoxVal").val(catId);
var textBoxValueData = $("#textBoxVal").val();
$.ajax({
url: '/Home/Save?data=' + textBoxValueData,
dataType: 'json',
type: 'post',
});
});
Model
public class Select2Model
{
public string id { get; set; }
public string text { get; set; }
}
C#
public JsonResult GetCategory(string searchTerm)
{
var list = new List<Select2Model>();
using (OracleConnection conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["PatientRecord"].ConnectionString))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = #"SELECT PATIENT, NAMEFORWARD FROM PATIENTDEMO ";
cmd.CommandType = CommandType.Text;
OracleDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
list.Add(new Select2Model()
{
text = rdr["NAMEFORWARD"].ToString(),
id = rdr["Patient"].ToString()
});
}
var dataList = list.ToList();
if (searchTerm != null)
{
dataList = list.Where(x => x.text.Contains(searchTerm)).ToList();
}
var modifiedData = dataList.Select(x => new {
id = x.id,
text = x.text
});
return Json(modifiedData, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Save(string data)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
600000 rows in a drop down list is not a user friendly one. Instead why don't you implement a drop down list with auto complete?
Check the example at the bottom of this page: https://api.jqueryui.com/autocomplete/
Update:
In your case you source would be a ajax call to the server side to pull the relevant data. Like this:
$('#myautocomplete').autocomplete({
type: "POST",
minLength: 3,
source : function (request, response)
{
var source_url = "../handlers/MyLookup.ashx?someparameter=" + $("#someparameter").val();
$.ajax({
url: source_url,
dataType: "json",
data: request,
success: function (data) { response(data); },
error : function (a,b,c) { HandleLookUpError(a); }
});
},
select: function (event, ui) { $('#result').val(ui.item.id); }
});
Note the source_url variable and the ajax call in the above code.
More details on how to load data from server side is here: https://stackoverflow.com/a/8873641/218408

DropDownList bind from web service Not passing data source when Edit in asp.net

I am using web service to bind data in DropDownList when I Add New data drop down list working fine, but when I Edit mode drop data source not fill. so the question is how to fill data source when I am using web service to bind web service.
Html:
<asp:DropDownList ID="cmbFlightNo" class="form-control" runat="server" DataValueField="mFlightNo" DataTextField="mFlightNo" AppendDataBoundItems="true">
</asp:DropDownList>
webservies
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
string Conec = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
SqlConnection con = new SqlConnection(Conec);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select FlightNo from AirLine_Flights where ALCode='" + StuID + "' and IsActive=1", con);
DataTable st = new DataTable();
da.Fill(st);
List<Airline_Flights> details = new List<Airline_Flights>();
foreach (DataRow dtrow in st.Rows)
{
Airline_Flights obj = new Airline_Flights();
obj.mFlightNo = dtrow["FlightNo"].ToString();
details.Add(obj);
}
JavaScriptSerializer ser = new JavaScriptSerializer();
return details.ToArray();
}
JQuery code to fill when change when fire.
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax(
{
type: "POST",
contentType: "application/json;charset=utf-8",
url: "AirlinesDropDown.asmx/Loadetails",
data: JSON.stringify({StuID: StuID }),
dataType: "json",
success: function (data) {
var theDropDown = document.getElementById("ContentPlaceHolder1_cmbFlightNo");
theDropDown.length = 0;
$.each(data.d, function (key, value) {
$("#ContentPlaceHolder1_cmbFlightNo").append($("<option></option>").val(value.mFlightNo).html(value.mFlightNo));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
var flightsList = GetFlightListByStuID(string StuID);
return selectedFlights.Select(x => x.FlightNo).ToArray();
}
// could be in another data access class etc.
private List<Airline_Flights> GetFlightListByStuID(string StuID)
{
List<Airline_Flights> selectedFlights = new List<Airline_Flights>();
string connectionString = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
// SQL with parameter
string commandString = #"
SELECT FlightNo
FROM AirLine_Flights
WHERE ALCode = #StuID AND IsActive=1
";
// use IDisposable here so it closes and garbage collects automatically
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandString))
{
// check the length and type here...
command.Parameters.Add("#StuID",SqlDbType.NVChar, 25).Value = StuID;
command.CommandType = CommandType.Text;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
flightsList.Add(new Airline_Flights{ FlightNo= reader["FlightNo"].ToString()});
}
}
}
}
return selectedFlights;
}
JavaScript
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax({
type: "POST",
contentType: "application/json",
url: "AirlinesDropDown.asmx/Loadetails",
data: {StuID: StuID},
dataType: "json"
})
.done(function(data) {
// verify data
alert(JSON.stringify(data));
// or
console.log(data);
var theDropDown = $("ContentPlaceHolder1_cmbFlightNo");
theDropDown.html(""); // clear old options
var options = [];
$.each(data.d, function(key, value) {
var opt = ("<option></option>").val(value.FlightNo).html(value.FlightNo))
options.push(opt);
});
$.each(options,function(v){theDropDown.append(v);});
})
.fail(function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internal Server Error.');
} else {
alert('Unknown Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}

how to display Highcharts from database in C# .Net

I have seen this http://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/ link and followed every steps but dint get the output(i have used "public class cityPopulation") in code behind instead of asmx page will it be the error
</head>
<body>
<script>
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: "aspchartjsdemo.aspx/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>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlyear" runat="server" >
<asp:ListItem>2010</asp:ListItem>
<asp:ListItem>2011</asp:ListItem>
<asp:ListItem>2012</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnCreatePieChart" runat="server" Text="Button" />
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
</div>
</form>
</body>
</html>
here is my Code Behind..Im Unable to Fetch the data from database.
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
using (NpgsqlConnection con = new NpgsqlConnection("Server=Localhost;Port=5432;User Id=postgres;Password=postgres;Database=database4;"))
{
string myQuery = "SELECT id_, city_name, population FROM tb_city_population WHERE year_of = #year";
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#year", pData[0]);
cmd.Connection = con;
con.Open();
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
cityPopulation cpData = new cityPopulation();
cpData.city_name = dr["city_name"].ToString();
cpData.population = Convert.ToInt32(dr["population"].ToString());
p.Add(cpData);
}
}
}
return p;
}
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
Any Help Highly appreciated..
This is how I build the Pie:
<div id="pieChart"></div>
<script type="text/javascript" src="highcharts.js"></script>
<script>
var myPieData = [ ['AAA', 34.03], ['BBB', 27.01], ['CCC', 18.77], ['DDD', 11.01], ['EEE', 5.91], ['FFF', 3.27] ];
chart = new Highcharts.Chart({
chart: {
renderTo: 'pieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'My PieData'
},
tooltip: {
pointFormat: '<b>{point.percentage:.2f}%</b>',
percentageDecimals: 2
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'default',
dataLabels: {
enabled: false,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: '',
data: myPieData
}]
});
</script>
The part you have to replace with your own data is [ ['Label A', 34.03], ['Label B', 27.01], ['Label C', 18.77], ['Label D', 11.01], ['Label E', 5.91], ['Label F', 3.27] ]
Of course the total value of all the data should be 100.00%
You can do that with a Literal or a string that is filled with content from code behind: var myPieData = [ <%= pieData %> ] or get it from an external source.
Depending on your localization settings, a numeric value can contain a "," instead of a "." (23,59 or 23.59). If your localization uses a "," you will have to replace that with a dot.
UPDATE
As requested an example of how to get a correct string that you can use to build the pie. This should get you started... Just make sure that population is in percentages, not absolute numbers.
public string getCityPopulation(List<string> pData)
{
StringBuilder sb = new StringBuilder();
string myQuery = "SELECT city_name, population FROM tb_city_population WHERE (year_of = #year)";
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand(myQuery, connection))
{
command.Parameters.AddWithValue("#year", pData[0]);
try
{
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sb.Append("[");
sb.Append("'" + dr["city_name"].ToString() + "'");
sb.Append(", ");
sb.Append(dr["population"].ToString().Replace(",", "."));
sb.Append("],");
}
}
}
catch
{
//error connecting\reading the database
}
}
return "[ " + sb.ToString().TrimEnd(',') + " ]";
}

Ajax call to get data to highchart

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.

Categories

Resources