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?
Related
I was trying to call the boolean from my Controller which is true, But when I call it now on my Javascript ajax I can't get it.
$.ajax({
url: "/Shop/Accessories",
contentType: "application/html; charset=utf-8",
type: 'GET',
dataType: "html",
success: (function (result) {
if (result) { //If I do result == true : still not working
$('#owl1').html(result)
$('#owl1').owlCarousel({
loop: true,
nav: false,
dots: false,
autoplay: false,
margin: 10,
responsive: {
0: {
items: 2
},
600: {
items: 3
},
1000: {
items: 4
}
}
})
} else {
$(".noItem1").html(result);
}
}),
error: (function (xhr, status) {
alert(status);
})
})
I am using a dataType: html for the return View when the database doesn't have any data
using (SqlConnection con = new SqlConnection(constring))
{
string command = "select item_image, item_name, item_price item_number, item_type, date_added from cooking_items";
con.Open();
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.CommandTimeout = 60;
SqlDataReader Creader1;
Creader1 = cmd.ExecuteReader();
if (Creader1.HasRows == true)
{
con.Close();
con.Open();
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
con.Close();
return View("Cooking", dt);
}
else
{
return View("Cooking"); //When there's no data, these is the one who should call my ajax.
}
}
}
Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
i try show error message
i have a link button in grid view ..i call highcharts when i click on this link button and also this static function.. through this static function i get data and then call this function through javascript so when i click on this button chart is display but when there is no chart it shows error in code so for this i want to show alert box when there is no chart..
public static function(int ID)
try
{
}
catch (Exception ex)
{
Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>");
}
i try above but this shows error message
Error 3 An object reference is required for the non-static field,
method, or property 'System.Web.UI.Page.Server.get'
Error 2 An object
reference is required for the non-static field, method, or property
'System.Web.UI.Page.Response.get'
lbViewChart is link button ...
jquery
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('[ID*=lbViewChart]').on('click', function () {
var row = $(this).closest('tr');
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVoiliations",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert('u');
//start
strArray = result.d;
var myarray = eval(strArray);
$('#container').highcharts({
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Contents of Highsoft\'s weekly fruit delivery'
},
subtitle: {
text: '3D donut in Highcharts'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
//end
},
error: function (error) {
alert(error);
}
});
}
// });
</script>
any solution?
You cannot access Server directly in a static method instead for that use System.Web.HttpContext.Current.Server So the code will be like:
System.Web.HttpContext.Current.Response.Write("<script>alert('" + System.Web.HttpContext.Current.Server.HtmlEncode(ex.ToString()) + "')</script>");
Or include using System.Web; to the using section and then use HttpContext.Current.Server
Updates: -
The HttpContext.Current is a static property so you can access it Directly inside a static method. and hence you can access .Server and .Response` from this as like the following:
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
currentContext.Response.Write("<script>alert('" + currentContext.Server.HtmlEncode(ex.ToString()) + "')</script>");
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;
}
});
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.