How to call json data on code behind - c#

<script type="text/javascript" language="javascript">
$(document).ready(function () {
var LastRecID = 1;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
var ImpData = document.getElementById('<%= hdnLanguage.ClientID %>').value;
if (LastRecID <= 1)
sendData();
LastRecID++;
}
});
function sendData() {
$.ajax(
{
type: "POST",
url: "try.aspx/GetData",
data: ImpData ,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "true",
success: function (msg) {
$("#myDiv").append(msg.d);
},
Error: function (x, e) {
alert("err");
}
});
}
});
</script>
I have hidden Field and it has same value. I set ImpData for hdnLanguage
var ImpData = document.getElementById('<%= hdnLanguage.ClientID %>').value;
I send data with Json:
data: ImpData
But I dont know how to call this data (ImpData) on code behind(in static web service). Thanks for your answer.

The data are translated to the GetData parameters. You if you send data like this:
data: { param1: ImpData }
Your GetData method has to have at least the param1 parameter:
public static void GetData(string param1)

I find answer
Json:
data: "{'Param': '" + Param + "'}"
Code Behind:
public static string GetData(string Param)
{
....
}

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) {
}
});

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.");
}
});
});

getting error on passing string as json object in ajax jquery

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"}),

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.

Categories