getting error on passing string as json object in ajax jquery - c#

I'm trying to pass a string in code behind method using ajax jquery but getting a stupid error. If I pass integer only then it works fine but in case of string it's not working
this is what i've tried
csharp code
public static string GetQuickVD(string key)
{
return key.ToString();
}
jquery
$(document).ready(function () {
GetQuickVL();
});
function GetQuickVL() {
var Nid = new Array();
for (var key in localStorage) {
if (key.substring(0, 4) == "vhs-") {
Nid += key.replace('vhs-', '') + ",";
}
}
$.ajax({
type: "POST",
url: "QuickViewList.aspx/GetQuickVD",
data: '{key: ' +'345,' + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.response);
},
error: function (response) {
alert(response.error);
}
});
}
function OnSuccess(response) {
alert(response.d);
}

use like this
data: {key: "345" }
You can also use like,
type: "GET",
url: "QuickViewList.aspx/GetQuickVD?key=355",
Edit
data: JSON.stringify({"key": "345"}),

Related

How to I pass parameters from ajax to web method?

I am doing a update operation from my web method. What I am doing is I have two text boxes inside my webForm1.aspx page. I am trying to post my these textboxes values to web method so my update operation will run. Below is my code:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: '{val1:"' + uval1 + '",val2:"' + uval2 + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
My update procedure is running fine but when I put debugging point on my web method and check parameters values it contain undefined values and don't getting correct values from text boxes. below is my codebehind code. Please help me here.
[WebMethod]
public static bool updateData(string val1,string val2)
{
var db = new dbDataContext();
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
return true;
}
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
and you must have to ensure that passed parameters must match webmethod params in server side.
[WebMethod]
public static bool updateData(string val1,string val2)
{
using (var db = new dbDataContext())
{
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
}
return true;
}
You need to send an array from the data parameter in ajax. Try something like:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}

Call WebMethod using jQuery

Hi i want to pass the values from jQuery and assign those values to a class model which is used in a method.
Following is my script:
$(document).ready(function(){
$('#BtnSubmit').click(function () {
var CollegeName = $('#TxtCollegeName').val();
var CollegeAddress = $('#TxtCollegeAddress').val();
var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
$.ajax({
type: 'Post',
url: pageUrl,
data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
},
error: function () {
alert("An error occurred.");
}
});
});
});
Below is my Csharp method:
[WebMethod]
public static string CreateCollegeData(CollegeDetails collegeDetails)
{
CollegeDAL obj = new CollegeDAL();
bool b = obj.InsertCollegeDetails(collegeDetails);
return "success";
}
But debugger is unable to call the web method. Every time the following message is coming:
Try declaring your object ahead of time: link
I got another solution.
$('#BtnSubmit').click(function () {
var collegeDetails = {};
collegeDetails.CollegeName = $('#TxtCollegeName').val();
collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();
$.ajax({
type: 'POST',
url: 'AddNewCollege.aspx/CreateCollegeData',
data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
$('#TxtCollegeName').val('');
$('#TxtCollegeAddress').val('');
},
error: function () {
alert("An error occurred.");
}
});
});

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.

returning complete page HTML instead of string output in JSON response

I am trying to achieve a simplest task through ajax using web method . My web method as follow
[WebMethod]
public static string GetDate()
{
return string.Format("says {0}", DateTime.Now.ToString("r"));
}
and ajax code as follow
$(document).ready(function() {
$("#Result").click(function() {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "test1.aspx/GetDate",
data : "{}",
contentType: "application/json",
dataType: "json text",
success: function(rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function(rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
console.log(rsp);
console.log(rsp.responseText);
}
});
});
});
but status says OK and 200 status code, but instead of simple string in rsp.d its shows complete HTML of that page self.
You Can Try this Code May be it is Help Full.
$("#Result").click(function () {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "Default.aspx/GetDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function (rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
}
});
});

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