response.data/ response.d displayed "undefined" - c#

I am trying to retrieve a list from C# code to an aspx page using ajax.
this is the ajax function:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: successRetireveGenders,
failure: function (response) {
alert("Error");
}
});
function successRetireveGenders(dataValues) {
alert(dataValues); // displayed [object object]
// but i actually have 2 rows result
alert(dataValues.data); //alert with "undefined"
alert(dataValues.d); //alert with "undefined"
// i try to put loop from 0 to response.d.length
for (var i = 0; i < dataValues.length; i++) {
alert(dataValues.length); //alert with "undefined"
alert(dataValues.d.length); //alert with "undefined"
}
I am always seeing an alert with message:
undefined
c# code:
[System.Web.Services.WebMethod]
public static List<ParticipantGender> getGenderCount()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
return ListOfParticipantGender;
}
ParticipantGender class:
public class ParticipantGender
{
public string gender;
public string cnt;
public ParticipantGender()
{
//
// TODO: Add constructor logic here
//
}
public ParticipantGender(string gender, string cnt)
{
this.gender = gender;
this.cnt = cnt;
}
}
EDIT:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
var callback = function (data, textStatus, xhr) {
alert("hi"); // not alerted
alert(data + "\t" + textStatus); // not alerted
};
EDIT:
i got in the console:
jsapi:23 A parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 jsapi:23 A parser-blocking, cross
site (i.e. different eTLD+1) script,
https://www.google.com/uds/api/visualization/1.0/40ff64b1d9d6b3213524485974f36cc0/format+en,default+en,ui+en,corechart+en.I.js,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 fontawesome-webfont.woff2:1 Failed
to load resource: the server responded with a status of 404 (Not
Found)

You should serialize the List<ParticipantGender> to JSON. You can install package Newtonsoft.Json which provides a lot of features.
For your case
using System.Configuration;
using Newtonsoft.Json;
[System.Web.Services.WebMethod]
public static string getGenderCount()
{
var connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var ListOfParticipantGender = new List<ParticipantGender>();
using(var conn = new SqlConnection(connStr))
{
conn.Open();
using(var cmd = new SqlCommand("getGenderCount", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using(var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read()) {
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
}
);
}
}
}
}
}
var json = JsonConvert.SerializeObject(ListOfParticipantGender);
return json;
}
Define the Callback function with necessary parameters and assign it to the $.ajax success event.
Also, there is no such event failure for $.ajax instead use error
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
};
Assign this callback to the success event
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: {},
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});

Related

Not Receiving the query result to ajax function from asmx page asp.net

I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});

Alert from back-end

This is a WebMethod that takes value from front-end in the lvl string.
Later that string is checked through getDuplicate procedure if there is already that value in the database. If the value exists then the insert procedure InsertObject is not activated and if there is no such value in the database first procedure returns null and the insert procedure will work.
Everything work well in the code all I need is some kind of an alert message from the C# part of the code if the insert is a success, and if it fails.
I tried so many examples and I can't find any solution :/
Can someone please help ?
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
cmdCount.CommandType = CommandType.StoredProcedure;
cmdCount.Parameters.AddWithValue("#ObjekatName", lvl);
var count = (string)cmdCount.ExecuteScalar();
if (count == null)
{
SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("#ObjekatName", lvl);
cmdProc.ExecuteNonQuery();
//successful alert
}
else
{
//fail alert
}
}
catch
{
}
finally
{
connection.Close();
}
return;
}
Update:
Ajax that sends values to the method:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
You can return a json object. Change the return type of method as string.Include using Newtonsoft.Json; and then when you want to return, create an object like this:
[WebMethod]
public static string GetCollection(string lvl)
{
bool isInserted = false;
// set the value of isInserted
// you can send code a numeric value or bool value according to your need
var result = new {code = isInserted, message = isInserted ? "Succesfully inserted" : "Already Exists"};
return JsonConvert.SerializeObject(result);
}
At the client side, check the response
success: function (response) {
console.log(response);
if(response != null){
var data = $.parseJSON(response)
alert(data.message)
}
location.reload(true);
}

asp.net webservice jquery textbox autocomplete

I'm trying to implement jquery - textbox autocomplete. for this setup a web service.
[WebMethod]
public List<Condition> GetCondition(string term)
{
List<Condition> listCondition = new List<Condition>();
string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelCondition", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
}
return listCondition;
}
}
public class Condition
{
public string ConditionName { get; set; }
public string ConditionID { get; set; }
}
WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.
<script type="text/javascript">
$(document).ready(function () {
$('#txtCondition').autocomplete({
source: function (request, response) {
$.ajax({
url: 'ibs_ws.asmx/GetCondition',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: request.term }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
})</script>
When I access the webservice it takes the #term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].
What could be the problem.
--
Thanks & Regards
May be it will help you. try this
I think you need to use $.map(data.d, function (value, key) {}). here is the example need to update your success code like below then you can get value inside object.
success: function (data) {
response($.map(data.d, function (value, key) {
return {
ConID: value.ConditionID,
ConNAme: value.ConditionName,
}
}))
},
AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.

Sending multiple parameters to stored procedure with jQuery Ajax

I've got a web method that looks like:
[WebMethod]
public void InsertDrugNameAndColorToDatabase(string drugName,string drugColor)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertDrugText", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#drugName", drugName);
cmd.Parameters.AddWithValue("#drugColor", drugColor);
cmd.ExecuteNonQuery();
}
}
}
and a little JS:
<script type="text/javascript">
$(document).ready(function () {
$(".drugQuizzes").draggable({ tolerance: "fit" });
$(".drugAnswers").droppable({
drop: function (event, ui) {
var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
console.log(drugColor);
console.log(drugName);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: drugName,
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".drugQuizzes").draggable({ tolerance: "fit" });
$(".drugAnswers").droppable({
drop: function (event, ui) {
var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
console.log(drugColor);
console.log(drugName);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: drugName,
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
});
</script>
I have a version of the stored procedure ans JS where only one parameter is sent to the stored procedure, and that works.
From the console.log(drugName) and console.log(drugColor) I get
{"drugColor":"rgb(255, 69, 0)"}
{"drugName":"ORACEA"}
How can I make the data parameter of the ajax call take multiple parameters at once?
What are some names of general techniques that I need to be aware of for sending more than one parameter to a stored procedure at once using jQuery ajax?
Consider building an object literal on the client-side and passing that entire object to the service, thus you have one parameter in your service call, like this:
Client-side:
var myData = {};
myData.DrugName' = $(ui.draggable).find("span").text();
myData.DrugColor' = $(ui.draggable).css("background-color");
// Create a data transfer object (DTO) with the proper structure, which is what we will pass to the service.
var DTO = { 'theData' : myData };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: JSON.stringify(DTO),
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
Now on the service-side, you will need to build a class that represents the contents of the object literal created above, like this:
public class ServiceData
{
public string DrugName { get; set; }
public string DrugColor { get; set; }
}
Finally, change your web service code to accept one parameter, like this:
[WebMethod]
public void InsertDrugNameAndColorToDatabase(ServiceData theData)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertDrugText", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#drugName", theData.DrugName);
cmd.Parameters.AddWithValue("#drugColor", theData.DrugColor);
cmd.ExecuteNonQuery();
}
}
}
Note: The data passed from the jQuery call is automatically matched up with the class properties you have in your ServiceData class as long as the names match on both the client-side and server-side.
You can specify multiple data items like:
data: 'drugName='+ drugName + '&drugColor=' + drugColor;
You don't need to stringify it at all, you can pass the parameters as an object. Try this:
$(".drugAnswers").droppable({
drop: function (event, ui) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: {
'drugName': $(ui.draggable).find("span").text(),
'drugColor': $(ui.draggable).css("background-color")
},
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
The ajax() function will then stringify it for you and pass it across to your C# endpoint.

jQuery autocomplete shows undefined values while WebService is returning correct data

$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D

Categories