Displaying two Google Graphs - javascript

I am trying to display 2 Google Graphs on my web page. Currently I can display the one without a problem.
The trouble comes in when I'm trying to display the other graph under the first one.
my front end code looks like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'MindYourMatterDash.aspx/GetData',
data: '{}',
dataType: "json",
success:
function (response) {
drawVisualization(response.d);
},
error: function (result) {
console.log(result);
alert("Please Contact Support with the following code in the subject :404 graph");
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, { title: "Broken PTP's Graph" });
}
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'MindYourMatterDash.aspx/GetDataFollowing',
data: '{}',
dataType: "json",
success:
function (response) {
drawVisualization(response.d);
},
error: function (result) {
console.log(result);
alert("Please Contact Support with the following code in the subject :404 graph");
}
});
})
function drawVisualization2(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('FollowGraph')).
draw(data, { title: "Follow Ups Graph" });
}
</script>
and the code behind the page:
[WebMethod]
public static List<Data> GetData()
{
string cat = "";
int val = 0;
DataTable dt = new DataTable();
cQuery _GraphInfo = new cQuery();
_GraphInfo.Sqlstring = "SQL Statement";
DataSet ds = _GraphInfo.SelectStatement();
dt = ds.Tables[0];
List<Data> datalist = new List<Data>();
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
datalist.Add(new Data(cat, val));
}
return datalist;
}
[WebMethod]
public static List<Data> GetDataFollowing()
{
string cat = "";
int val = 0;
DataTable dt = new DataTable();
cQuery _GraphInfo2 = new cQuery();
_GraphInfo2.Sqlstring = "SQL Statement";
DataSet ds = _GraphInfo2.SelectStatement();
dt = ds.Tables[0];
List<Data> datalist2 = new List<Data>();
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
datalist2.Add(new Data(cat, val));
}
return datalist2;
}
Currently when this code runs it loads the first graph and then replaces the first graph with the second one instead of loading it into the second div tag.
Any help would be greatly appreciated.

Related

How to push data to create pie chart - chart js

I have data from SQL in json code file (checked in Fiddler)
{"d":[{"__type":"Dashboards.Employee","name":"Test
Hen","turnover":"1500000,0000","color":"#231F20"},{"__type":"Dashboards.Employee","name":"Test
Bai","turnover":"130000,0000","color":"#FFC200"}]}
but i dont know, how to push them correctly in order to create pie chart
my ajax/javascript is here:
$.ajax({
url: 'HelloService.asmx/GetEmployeeDetail',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ month: number }),
dataType: 'json',
method: 'post',
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = [];
//var ctx = document.getElementById('pele').getContext('2d');
$.each(aData, function (inx, val) {
var obj = {};
obj.label = val.name;
obj.value = val.turnover;
obj.color = val.color;
arr.push(obj);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(arr);}
function OnErrorCall_(response) {
console.log(error);
}
});
});
Am I missing something?
If i use static values (value, label, color) pie chart works without problem.
Thank you
I created the following FiddleJS for you: https://jsfiddle.net/cukyrh5h/1/
You need to replace the URL of the Ajax call with yours of course. You had some wrong syntax (too much braches in the end of your Snippet) and the API you were using was not working with ChartJS 2.4 anymore.
The code looks like the following:
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:OnSuccess_
});
function OnSuccess_(response) {
var aData = response.d;
var data = {
labels: [],
datasets: [{
data: [],
backgroundColor: []
}]
};
$.each(aData, function (inx, val) {
data.labels.push(val.name);
data.datasets[0].data.push(val.turnover);
data.datasets[0].backgroundColor.push(val.color);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
function OnErrorCall_(response) {
console.log(error);
}
Ok, i found problem, why i cant see my Chart. Maybe it will be useful for another members. Data in Database (turnover was daclared as money, i changed it to int .... and it works)

Uncaught Error: Not an Array - google charts

I need help with an ajax call I am performing, I am passing back an array from the backend as seen below, if I alert the data on the front end I get this.
However when I pass it through, google charts tells me it's not an array.
Uncaught Error: Not an array
at gvjs_oba (format+en_GB,default+en_GB,ui+en_GB,corechart+en_GB.I.js:272)
at new gvjs_Pl (format+en_GB,default+en_GB,ui+en_GB,corechart+en_GB.I.js:274)
at drawChart (Default.aspx:60)
at Object.success (Default.aspx:43)
at j (jquery-1.11.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.1.min.js:2)
at x (jquery-1.11.1.min.js:4)
at b (jquery-1.11.1.min.js:4)
at Object.send (jquery-1.11.1.min.js:4)
at Function.ajax (jquery-1.11.1.min.js:4)
Ajax Query
<script lang="javascript">
var chart_data;
var startdate = "default";
var enddate = "default";
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(load_page_data);
function load_page_data()
{
$.ajax({
type: "post",
url: 'feed.aspx/GetJsonwithStringBuilder',
data: JSON.stringify({y: $('input[name=yaxis]:checked').val()}),
contentType: "application/json; charset=utf-8",
dataType: "text",
async: false,
success: function (data) {
if (data) {
drawChart(data, "My Chart", "Members");
}
},
error: function () {
alert('error');
}
});
}
function drawChart(chart_data, chart1_main_title, chart1_vaxis_title) {
var chart1_data = new google.visualization.arrayToDataTable(chart_data);
var chart1_options = {
title: chart1_main_title,
hAxis: { title: 'Month', type: 'string' },
seriesType: 'bars',
vAxis: { title: chart1_vaxis_title, titleTextStyle: { color: 'red' } }
};
var chart1_chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart1_chart.draw(chart1_data, chart1_options);
}
</script>
This is the backend
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetJsonwithStringBuilder(string y)
{
DataTable dsChartData = new DataTable();
StringBuilder strScript = new StringBuilder();
try
{
dsChartData = GetChartData();
strScript.Append("[[");
foreach (DataColumn column in dsChartData.Columns)
{
strScript.Append("\"" + column.ColumnName + "\",");
}
strScript.Remove(strScript.Length - 1, 1);
strScript.Append("],");
foreach (DataRow row in dsChartData.Rows)
{
strScript.Append("[");
foreach (DataColumn column in dsChartData.Columns)
if (column.ColumnName == "Month")
strScript.Append("\"" + CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(Int32.Parse(row[column.ColumnName].ToString())) + "\",");
else if (IsNumber(row[column.ColumnName].ToString()))
strScript.Append("" + row[column.ColumnName] + ",");
else
strScript.Append("\"" + row[column.ColumnName] + "\",");
strScript.Remove(strScript.Length - 1, 1);
strScript.Append("],");
}
strScript.Remove(strScript.Length - 1, 1);
strScript.Append("]");
return strScript.ToString();
}
catch (Exception ex)
{
}
finally
{
dsChartData.Dispose();
strScript.Clear();
}
return "";
}
You need to use data.d instead of data in success function
$.ajax({
type: "post",
url: 'feed.aspx/GetJsonwithStringBuilder',
data: JSON.stringify({y: $('input[name=yaxis]:checked').val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
var dataObj=JSON.parse(data.d);
if (dataObj) {
drawChart(dataObj, "My Chart", "Members");
}
},
error: function () {
alert('error');
}
});
success: function (data) {
drawChart(JSON.parse(data.d), "My Chart", "Members");
},
Can you try this?

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

how to get the checkbox in edit modal popup in MVC-4

I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...
For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});

How to list autocomplete results as a link?

I am new on Ajax. I need to find how to list autocomplete results as a link. When user clicks the result should open that link. I can list the related result but I couldn't find how to add the links. It should be added somewhere in the script as a html tag. Please give me some clue how to add html link
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'question':'" + document.getElementById('txtQuestion').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
Here is the method which connects to the db and returns related results:
[WebMethod]
public static List<string> GetAutoCompleteData(string question)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx+"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Questions,Link FROM DigiQA WHERE Questions LIKE '%'+#quest+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#quest", question);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Questions"].ToString());
}
return result;
}
}
}
Try something like this
success: function(data) {
response($jQuery.map(data, function(item) {
return {
label: '' + item + ''),
value: item
}
}))
}

Categories

Resources