google.visualiztion.ColumnChart() dont work - c#

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.

Related

Display message(there is no data available) or empty graph for google pie chart if data is zero using asp.net web form

Display message(there is no data available) or empty graph for google pie chart if data is zero using asp.net web form
Below is my script
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
// Load the Visualization API and the corechart package.
google.charts.load('current', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
$.ajax({
type: "POST",
url: "add_claim.aspx/Fillgraph",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r.d === null) {
document.getElementById('piechart').innerHTML = 'No data found.';
return;
}
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('string', 'Topping');
chartdata.addColumn('number', 'Slices');
chartdata.addRows(r.d);
// Set chart options
var options = {
pieHole: 0.6,
legend: { position: 'bottom' },
width: '100%',
height: '100%',
pieSliceText: 'percentage',
colors: ['#1e93c6', '#d6563c', '#c79f49', '#ff9a00'],
chartArea: {
left: "3%",
top: "5%%",
height: "95%",
width: "94%"
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(chartdata, options);
},
failure: function (r) {
// alert(r.d);
},
error: function (r) {
// alert(r.d);
}
});
}
})
</script>
Below is my code behind c#
[WebMethod]
public static List<object> Fillgraph()
{
BusinessLogic bl = new BusinessLogic();
BusinessObject bo = new BusinessObject();
List<object> chartData = new List<object>();
bo.Para1 = "1";//#ParaValues
bo.Para2 = System.Web.HttpContext.Current.Session["UserId"].ToString();//#username
bo.Para3 = System.Web.HttpContext.Current.Session["UniqueID"].ToString();//#username
DataTable dt = bl.ACS_Get_Graphs(bo);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Food"].ToString() != "")
{
chartData.Add(new object[] { "Food", Convert.ToInt32(dt.Rows[0]["Food"].ToString()) });
}
else
{
chartData.Add(new object[] { "Food", 0 });
}
if (dt.Rows[0]["LocalConveyance"].ToString() != "")
{
chartData.Add(new object[] { "Local conveyance", Convert.ToInt32(dt.Rows[0]["LocalConveyance"].ToString()) });
}
else
{
chartData.Add(new object[] { "Local conveyance", 0 });
}
if (dt.Rows[0]["Lodging"].ToString() != "")
{
chartData.Add(new object[] { "Lodging", Convert.ToInt32(dt.Rows[0]["Lodging"].ToString()) });
}
else
{
chartData.Add(new object[] { "Lodging", 0 });
}
if (dt.Rows[0]["MisExpences"].ToString() != "")
{
chartData.Add(new object[] { "Misc. Expences", Convert.ToInt32(dt.Rows[0]["MisExpences"].ToString()) });
}
else
{
chartData.Add(new object[] { "Misc. Expences", 0 });
}
if (dt.Rows[0]["Travelling"].ToString() != "")
{
chartData.Add(new object[] { "Travelling", Convert.ToInt32(dt.Rows[0]["Travelling"].ToString()) });
}
else
{
chartData.Add(new object[] { "Travelling", 0 });
}
return chartData;
}
else
{
return null;
}
}
if Local conveyance=0 , Lodging=0 , Misc. Expences=0 and Travelling=0 then message should display there is no data availabe
or show empty pie graph
I tried below example but not able to getting
How to display "No Data" message in the middle of chart area in column chart
Google Charts - No data available - Able to display a blank chart?
JavaScript Debugger Image
You could return null from the WebMethod if there was no data
if (dt.Rows.Count > 0)
{
//rest of code
}
else
{
return null;
}
Then check for null in the drawChart function at the top of success: function (r)
function drawChart() {
$.ajax({
type: "POST",
url: "add_claim.aspx/Fillgraph",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r.d === null) {
document.getElementById('piechart').innerHTML = 'No data found.';
return;
}
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('string', 'Topping');
chartdata.addColumn('number', 'Slices');
//rest of javascript code
The answers you have placed correspond to a LineChart, in your example you are using a PieChart, try replacing this:
JS Code:
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(chartdata, options);
for this:
JS Code:
if (chartdata.getNumberOfRows() == 0) {
var d = document.getElementById("piechart");
d.innerHTML = "<p>Sorry, not info available</p>";
// Custom style
d.style.position = "relative";
d.style.fontSize = "25px";
d.style.right = "50%";
d.style.left = "50%";
}
else {
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(chartdata, options);
}
References: how to change the text 'no data' in google pie chart

Bings Maps - Read GeoJSON

I am working with the Bing Maps v8 API, trying to load my own GeoJSON onto a Bing Maps as in this example: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#geoJsonReadObject+JS
I am creating my JSON successfully (I have tested it using the Bing Maps Drag and Drop feature and all of my points show on the map. https://bingmapsv8samples.azurewebsites.net/#GeoJson%20Drag%20and%20Drop.
I am trying to get my GeoJSON to automatically load on a map, and I am receiving a JSON failure, and I am not sure why. (I am rather new to GeoJSON/JSON.)
Javascript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
var featureCollection = Microsoft.Maps.GeoJson.read(getGeoJson(), { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
function getGeoJson() {
$(function (callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
});
}
}
Controller:
[HttpPost]
public JsonResult PatGeoJSON(string parent)
{
JObject jsondata = JObject.FromObject(new
{
type = "FeatureCollection",
features = from p in pList
select new
{
type = "Feature",
geometry = new Geometry
{
type = "Point",
coordinates = new double?[] { p.GeoLocation.Longitude, p.GeoLocation.Latitude }
},
properties = new Properties
{
MemberName = p.MemberName,
/// etc...
}
}
});
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
My result is currently a "Failure" alert with the JSON string. Note: if I hardcode my GeoJSON as the result from the getGEOJSON function, all of my points show up on the map. Am I not reading the JsonResult correctly in my script?
Your getGeoJson function is asynchronous, so it doesn't return anything, this bing maps is receiving a null value to parse which it simply ignores and this no error. Specify a callback function when loading your geojson and when it responds, then read its value. Here is an updated version of your JavaScript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
getGeoJson(function(data){
var featureCollection = Microsoft.Maps.GeoJson.read(data, { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
});
function getGeoJson(callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
}
}

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.

Bind longitude and latitude from Code behind on Google Maps API Version3 in ASP.NET

Source Code aspx page:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function loadData(e) {
e.preventDefault();
var ltlng = [];
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/getData",
dataType: "json",
success: function (data) {
$(data.d).each(function (index, item) {
var firstValue = parseFloat(item.FirstValue).toFixed(2);
var secondValue = parseFloat(item.SecondValue).toFixed(2);
ltlng.push(new google.maps.LatLng(firstValue, secondValue));
});
},
error: function () {
alert("Error");
}
});
//alert("Test");
markicons(ltlng);
}
var map; var infowindow;
function InitializeMap() {
var latlng = new google.maps.LatLng(40.756, -73.986);
var myOptions =
{
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function markicons(ltlng) {
InitializeMap();
map.setCenter(ltlng[0]);
for (var i = 0; i <= ltlng.length; i++) {
if (ltlng[i] != undefined) {
marker = new google.maps.Marker({
map: map,
position: ltlng[i]
});
alert(ltlng[i]);
(function (i, marker) {
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent("Message" + i);
infowindow.open(map, marker);
});
})(i, marker);
}
else {
}
}
}
window.onload = loadData;
</script>
<div id="map" style="width: 800px; height: 500px;">
</div>
Source Code for C#:
[WebMethod]
public static object getData()
{
var obj = new { FirstValue = 17.22, SecondValue = 78.28 };
var objList = (new[] { obj }).ToList();
objList.Add(new { FirstValue = 13.5, SecondValue = 79.2 });
objList.Add(new { FirstValue = 15.24, SecondValue = 77.16 });
return objList;
}
I am getting the result like this,
Tested Browser : Google Chrome. Please suggest me how can i resolve from this error.
You are calling your markicons(ltlng); method after you initialize your ajax request for the data.
You need to call this method AFTER you have got your data back.
Example:
success: function (data) {
$(data.d).each(function (index, item) {
var firstValue = parseFloat(item.FirstValue).toFixed(2);
var secondValue = parseFloat(item.SecondValue).toFixed(2);
ltlng.push(new google.maps.LatLng(firstValue, secondValue));
});
// Call method here.
markicons(ltlng);
},

JQuery Dialog and multi Mvc4 PartialView

i have a View, and on a button click i need that open me a JQueryDialog loaded from PartialView that have inside a list of items... on click of one of these items, i need that in the same JQueryDialog open another PartialView, for editing this item, so a simple List/Detail nested in a JQueryDialog..
i post a sample..
http://sdrv.ms/15hG92K
VIEW
$('#dialogReferences').dialog({
autoOpen: false,
width: dWidth,
resizable: false,
title: 'TEST',
modal: true,
draggable: false,
position: ['top', 100],
open: function (event, ui)
{
var id = $(this).data('id');
var url = '#Url.Action("ListItem", "Home")';
$(this).dialog().load(url, function ()
{
$(document).unbind("click", ".k-grid-Edit").on("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
}
});
EDIT
$(document).ready(function ()
{
$.ajaxSetup({ cache: false });
$(document).unbind("click","#btnCancel").one("click", "#btnCancel", function (evt)
{
evt.preventDefault();
var model = #Html.Raw(Json.Encode(Model));
var urlList = '#Url.Action("ListItem", "Home")';
$('#dialogReferences').dialog().load(urlList, function ()
{
$(document).unbind("click", ".k-grid-Edit").one("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
})
});
if i try to 'open file dialog' and delete without edit, it call delete action one time, and it's ok.
but if you try to enter in edit and than come back with cancel to the list, and delete, it call twice.
Someone can give me and advice?

Categories

Resources