How can I call the boolean from c# to Javascript Ajax? - javascript

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.
}
}
}

Related

i have an error while export excel file using c# mvc

i am using asp.net mvc webapi and ajax in my project
i am calling controller using ajax and sending data with ajax
here is my ajax code
var bobj = {};
bobj.data = data;
CallAjax('post',common,'attendancesheetdownload',bobj,_getholidaylist.onsuccestendancesheetdownload, '');
function CallAjax(method, baseUrl, strUrl, strData, onSuccess, onFailure) {
callDebugger();
var dataValue = null;
var ContentType = "application/json; charset=utf-8";
strUrl = baseUrl + strUrl;
method = method.toUpperCase();
if (method == "GET") {
dataValue = strData;
}
else if (method == "POST") {
dataValue = JSON.stringify(strData);
}
callLoader(true);
$.ajax({
type: method,
url: strUrl,//users/signin
contentType: ContentType,
dataType: 'json',
data: dataValue,
async: false,
success: onSuccess,
error: function (err) {
callLoader(false);
swal({
title:err, text: "", type: "error",
showCancelButton: false, closeOnConfirm: true, confirmButtonText: "OK",
}, function (isConfirm) {
window.location = "signin";
});
//console.log(err);
}
});
}
and here is my c# controller code for excel generate
[HttpPost]
[Route("attendancesheetdownload")]
public JsonResult AttendanceSheetDownload(List<AttendanceModel> data)
{
//List<AttendanceModel> holidaylist = new List<AttendanceModel>();
try
{
System.Data.DataTable dt = new System.Data.DataTable();
using (XLWorkbook wb = new XLWorkbook())
{
//DataTable dt = new DataTable();
dt.Columns.Add("Employee Name");
dt.Columns.Add("Leaves");
// dt.Columns.Add("URL");
foreach (var item in data)
{
var row = dt.NewRow();
row["Employee Name"] = item.user_id;
row["Leaves"] = Convert.ToString(item.days);
// row["URL"] = item.URL;
dt.Rows.Add(row);
}
// dt = attendacemodel;
wb.Worksheets.Add(dt, "CusDetail");
wb.ShowRowColHeaders = false;
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customers.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
return Json(data);
}
catch (Exception ex)
{
throw ex;
}
finally
{
data = null;
}
}
i dont see any error at c# side it easly pass all the step but the file is not downloading
and
when its comes to onsuccess method of ajax its give me object object error
can some one guide me how to download excel file with ajax c# and webapi

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?

Autocomplete textbox don't show result inside clicking of textbox

I have a autocomplete textbox which filters exactly what I want to search for. But now what I want is,
If user doesn't types anything into the textbox and just clicks the textbox. It should show all the result. Is this possbile ?
Below is my code.
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txt712").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
Also find the link from where I got the reference.
Reference link
UPDATE
Server side code
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (OracleConnection ObjPriCon = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString()))
{
using (OracleCommand cmd = new OracleCommand("select distinct survey_area_7_12 FROM xxcus.xxacl_pn_farming_mst WHERE survey_area_7_12 LIKE '%' || :searchtext || '%'", ObjPriCon))
{
ObjPriCon.Open();
cmd.Parameters.AddWithValue(":searchtext", username.ToLower());
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
result.Add(dr["survey_area_7_12"].ToString());
}
}
return result;
}
}
}
In Server code check if the search string is null or not and trigger the query accorduingly
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
**//check if user name is not null**
if(null != username){
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'+#SearchText+'%'", con))}
else{
using (SqlCommand cmd = new SqlCommand("select UserName from UserInformation, con))}
}
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
You can use "Focus" event to do this.
.focus(function () {
$(this).autocomplete("search");
});
Full code as below.
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
$(this).autocomplete("search"); //New Code
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});

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 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