I have a Morris chart that I try to use that gets data from an external source in this case an aspx page. But the chart is not displayed at all. The only chart that is displayed is the one I add static data to myfirstchart.
Anyone see what I am missing?
Chart page:
<head runat="server">
<title></title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
Morris.Donut({
element: 'morris-donut-chart',
data: $.parseJSON(Graph()),
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = result.d;
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="morris-donut-chart" style="height: 250px;"></div>
<div id="myfirstchart" style="height: 250px;"></div>
</div>
</form>
<script>
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value']
});
</script>
</body>
Data page:
protected void Page_Load(object sender, EventArgs e)
{
var sb = new StringBuilder();
sb.Append("[");
sb.Append(" { label: '2012-10-01', value: 802 },");
sb.Append(" { label: '2012-10-02', value: 783 },");
sb.Append(" { label: '2012-10-03', value: 820 },");
sb.Append(" { label: '2012-10-04', value: 839 },");
sb.Append(" { label: '2012-10-05', value: 792 },");
sb.Append(" { label: '2012-10-06', value: 859 },");
sb.Append(" { label: '2012-10-07', value: 790 },");
sb.Append("]");
var jsonSerializer = new JavaScriptSerializer();
string data = jsonSerializer.Serialize(sb.ToString());
string json = data;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
Use a WebMethod:
[WebMethod]
public static string getGraph()
{
List<object> json = new List<object>();
json.Add(new { label = "2012-10-01", value = 802 });
json.Add(new { label = "2012-10-02", value = 783 });
json.Add(new { label = "2012-10-03", value = 820 });
json.Add(new { label = "2012-10-04", value = 839 });
json.Add(new { label = "2012-10-05", value = 792 });
json.Add(new { label = "2012-10-06", value = 859 });
json.Add(new { label = "2012-10-07", value = 790 });
List<object> jsonObject = new List<object>();
jsonObject.Add(new {
graph = json
});
return new JavaScriptSerializer().Serialize(jsonObject); ;
}
And update your javascript with a call to the WebMethod getGraph:
$(document).ready(function () {
var graph = Graph();
Morris.Donut({
element: 'morris-donut-chart',
data: graph[0].graph,
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx/getGraph',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = $.parseJSON(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}
Related
i have to create a multiseries line chart which is to need view each series with the value of site id and each series with different position .Just now i'am stuck that can only view one series with one query.
And here is the aspx.vb page
Public Class WaterTreament
Public position As Integer
Public value As Double
Public timestamp As String
End Class
<WebMethod()>
Public Shared Function GetWaterTreament() As List(Of WaterTreament)
Using con As New SqlConnection("Data Source=DESKTOP-B8TBSJH1;Initial Catalog=SAY;Integrated Security=SSPI")
Using cmd As New SqlCommand("select position,dtimestamp ,value from telemetry_log_table where siteid ='S1-21' AND dtimestamp BETWEEN '2021-02-02' AND '2021-02-03' and position='62'and value>0 order by dtimestamp asc")
cmd.Connection = con
Dim wtp As New List(Of WaterTreament)()
con.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
wtp.Add(New WaterTreament() With {
.position = Convert.ToInt32(dr("position").ToString()),
.value = Convert.ToDouble(dr("value").ToString()),
.timestamp = dr("dtimestamp").ToString()
})
End While
End Using
con.Close()
Return wtp
End Using
End Using
End Function
Here is the script for highcharts.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetWaterTreament",
data: "{}",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
debugger;
var aData = response.d;
var arr = [];
var arr2 = [];
var timestamp = [];
$.map(aData, function (item, index) {
var i = [item.value];
var obj = {};
var obj1 = {};
var obj2 = {};
obj.name = item.position;
obj.y = item.value;
obj.y1 = item.timestamp;
obj2.data = item.timestamp;
arr.push(obj.y);
arr2.push(obj.y1);
timestamp.push(obj2.data);
console.log(obj2);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
//Second Value
var myJsonString1 = JSON.stringify(arr2);
var jsonArray1 = JSON.parse(JSON.stringify(arr2));
//third Value
var myJsonString2 = JSON.stringify(timestamp);
var jsonArray2 = JSON.parse(JSON.stringify(timestamp));
//alert(jsonArray);
DreawChart(jsonArray, jsonArray1, jsonArray2);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
});
function DreawChart(seriesData1, seriesData2, seriesData3) {
Highcharts.chart('container', {
// $('#container').highcharts({
title: {
text: 'SITE ID'
},
yAxis: {
title: {
text: 'Values',
}
},
xAxis: {
categories: seriesData3
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
}
},
series: [{
type: 'line',
name: 'PH',
data: seriesData1
},
{
type: 'line',
name: 'CHLORINE',
data: seriesData1
},
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
}`
What is your issue here exactly?
You may want to try official Highcharts .NET wrapper: dotnet.highcharts.com.
Sample chart and source code in C# with multiple series: https://dotnet.highcharts.com/Highcharts/Demo/Gallery?demo=LineBasic&theme=default
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!
I am trying to get the selected row of a MVCGrid and display the details in an modal dialog using a partialview.
I am getting the selected row via ajax:
$(document).ready(function(){
var selectedRow;
$(document).on('click', '.grid-mvc', function () {
pageGrids.PersonGrid.onRowSelect(function (e) {
// $.prompt(e.row.ID);
SendData(e.row);
});
});
});
The 'SendData'-function is:
function SendData(i) {
var data= i.ID;
$.ajax({
url: '/Home/Person',
contentType: "application/html; charset=utf-8",
type: "GET",
data: { "id": daten },
dataType: "html"
, success: function () {
ShowPersonDetails(data);
}
});
}
and the ShowPersonDetails(data) is like that:
function ShowPersonDetails(data) {
$(document).ready(function () {
$('#PersonDiv').load("Person?id=" + data);
$("#PersonDiv").prompt(
$("#PersonDiv").html(),
{
title: "some title",
buttons: { OK: 'true', Abbruch: 'false' },
position: { width: 800, height: 600 }
});
});
}
The controller:
[HttpGet]
public ActionResult Person(int id)
{
var pS = new DbAccess(MvcApplication.Connection).GetUserData(id);
var p = new Person();
if (pS.Rows.Count < 0)
{
return PartialView("Person");
}
p.Alter = pS.Rows[0].ItemArray[0].ToString();
p.Nachname = pS.Rows[0].ItemArray[5].ToString();
return PartialView("Person", p);
}
Any advice would be nice!
Greetings
PP
i did something like you are trying to do, so hope my code helps
in the grid, table, i put a link for details
<tr>
<td>
#Html.ActionLink("Details", "ActionDetails", new { id = Model.LstItems[x].ID }, new { #class = "detailsLink" })
</td>
</tr>
the javascript
$('#detailsDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".detailsLink").button();
$(".detailsLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#detailsDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
in somewhere in the view
<div id="detailsDialog" title="Offer Details">
</div>
the controller
public ActionResult ActionDetails(int id)
{
ItemEntity model = ItemEntity .GetBy(id);
return PartialView(model);
}
the partial view
#model YourNameSpace.Entities.ItemEntity
#using (Ajax.BeginForm("ActionDetails", "YourController", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess",
OnFailure = "showErrorMessage"
}, new { #id = "detailForm" }))
{
//your details for your item
}
hope this help you
I have li tags that includes links to different pages. Now i am trying to create a searcj by clicking on specific li tag. I want when user clicks on this li named 'Field Workers', a sub li appears that includes names of all field workers that are in the database. Ajax code is used to diaplay the field workers. I am getting data in the ajax cide but somehow it is not getting displayed. Can anyone help me with this?
Ajax code:
<script>
var ajaxOptions = {
type: "POST", url: null, success: null, async: true,
data: "", dataType: "json", contentType: "application/json; charset=utf-8"
}
$(function () {
BindFW();
})
function BindFW() {
ajaxOptions.data = "";
ajaxOptions.url = "WebForm1.aspx/BindFieldWorkers"
ajaxOptions.success = function (result) {
if (result.d != null && result.d != "") {
//$("#templateFW").tmpl(result.d).appendTo("#ulFW");
$.each(result.d, function () {
$('#ulFW').append();
});
}
}
$.ajax(ajaxOptions);
}
</script>
<ul>
<li class="has-sub">
<a href="javascript:;">
<i class="icon-search"></i>
<span class="title">Field Worker Name</span>
<span class="arrow "></span>
</a>
<ul id="ulFW" class="sub">
</ul>
</li>
</ul>
use from this script:
$(document).ready(function () {
BindFW(10);
});
function BindFW(StateId) {
var data = {
StateId: StateId
};
$.ajax({
type: 'POST',
url: './WebForm1.aspx/BindFieldWorkers',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(data),
success: function (data) {
if (!data.d['Result']) {
alert('no records found!');
return;
}
var records = data.d['Records'];
for (var i = 0; i < records.length; i++) {
$('#ulFW').append(function () {
return $('<li>').text(records[i].Text).attr('data-id', records[i].ID)
});
}
},
error: function (data) {
alert('failed to connect to server!');
}
});
}
and this in your code behind:
[System.Web.Services.WebMethod]
public static object BindFieldWorkers(int StateId)
{
try
{
List<object> result = new List<object>();
for (int i = 0; i < 10; i++)
{
result.Add(new
{
ID = i,
Text = "Text " + i
});
}
return new { Result = true, Records = result };
}
catch (Exception ex)
{
return new { Result = false, Message = ex.Message };
}
}
I want to create an Autocomplete field for a search option. I have tried with following code.
But the web method doesn't fire when the Autocomplete function is execution.
What will be the reason ?
Here is the jQuery function:
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
$.ajax ({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Here is the web method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}
Make sure you hit the webservice function by having breakpoint on your service function. Please change your script to below:
<script type="text/javascript">
$(function () {
$("#<%=tags.ClientID %>").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: " <%=ResolveUrl("~/Services/AutoComplete.asmx/GetFarmersByName") %>",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
response($(data.d, function (item)
{
return
{
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Above your service class add [System.Web.Script.Services.ScriptService]
Or you can do this in an asp.net page!
add the static keyword and change the webservice to ASP.NET page!
public static string GetFarmersByName(string name)
For example:
A.aspx:
$.ajax({
type: "POST",
url: "A.aspx/GetSN",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async:false,
success: function (json) {
var msg = JSON.parse(json.d);
sn = msg;
},
failure: function () {
alert("Sorry,there is a error!");
}
});
Then in your A.aspx.cs type in:
[WebMethod]
public static string GetSN()
{
Random RN = new Random();
string year = DateTime.Now.ToString("yy").ToString();
string MonAndDate = DateTime.Now.ToString("MMdd").ToString();
string Hour = DateTime.Now.ToString("HHMMss").ToString() + DateTime.Now.Millisecond.ToString() + RN.Next(100, 900).ToString();
string SerialNumber = year + MonAndDate + Hour;
return JsonConvert.SerializeObject(SerialNumber);
}
Assuming tags as your textbox, set data as { 'name': '" + request.term + "'}
$("#<%=tags.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
},
});
},
minLength: 0,
focus: function () {
// prevent value inserted on focus
return false;
},
});
debug on method GetFarmersByName,
NOTE: Check have you uncomment [System.Web.Script.Services.ScriptService] on .asmx page.
Post again!!!
Test.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function(){
$("#Button1").bind("click",function(){
$.ajax({
type: "POST",
url: "Test.asmx/GetFarmersByName",
data:"{'aaa':'zhangsan'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function (json) {
},
failure: function () {
alert("Sorry,there is a error!");
}
});
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
</body>
</html>
Test.asmx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace TestWebForm
{
/// <summary>
/// Summary description for Test
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Test : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
}
}
Paste this method inside code behind file where you are calling this method. Change url to url: "Test.aspx/GetFarmersByName" and then test it. Its much clean code rather then Web Service.
using System.Web.Script.Services;
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
try this -
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
var obj = JSON.Stringfy("{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}");
$.ajax ({
type: "POST",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
and the webmethod-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}