$.Ajax POST, accessing return data - c#

I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

try alert(result.d);

You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.

According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.

This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.

Related

jQuery ajax call doesn't seem to do anything at all

I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.

JQuery values passed to WebApi is always null

I am having trouble with Web Api and was hoping someone here might be able to help me.
I have a jQuery method as follows ...
function OnInsert(evt) {
var truckId = $("#txtTruckId").val();
var truckReg = $("#txtTruckReg").val();
var description = $("#txtDescription").val();
var condition = $("#txtCondition").val();
var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg +
'","Description":"' + description + '","Condition":"' + condition + '"}}';
var json = JSON.stringify(data)
$.ajax({
url: '/api/Values',
cache: false,
type: 'POST',
data: json,
dataType: 'json',
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
})
}
When I debug that the 'data' variable successfully captures the data.
I then have a function in my WebApi controller ...
// POST api/values
public void Post(TruckInfo obj)
{
WebApiTestEntities db = new WebApiTestEntities();
db.TruckInfoes.Add(obj);
db.SaveChanges();
}
However, when I debug thst all of the parameters are showing a null value.
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but that hasn't worked.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
I also found this which kind of comes up with an answer but after trying to alter my code so it looks like the code they have written it still doesn't work.
jQuery posts null instead of JSON to ASP.NET Web API
Is any one able to help?
Thanks in advance
Lex
Start by fixing your JSON:
var data = {
truckId: truckId,
reg: truckReg,
description: description,
condition: condition
};
var json = JSON.stringify(data);
and then make sure you specify the correct content type request header:
$.ajax({
url: '/api/Values',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: json,
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
});
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but
that hasn't worked.
No, no, no. Not necessary as long as you format properly your JSON request, the Web API will bind it to your model.

JSON stringify to C# Webservice

I know there are a few questions out there but I've tried a lot of them and I'm still not able to even get my script to make it to the server. Here is what I currently have:
Javascript
function UpdateSessionUser(user)
{
if (user != null)
{
var targetPage = "http://" + document.location.host + "/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser";
var dataText = { "jsonUser" : JSON.stringify(user) };
try
{
$.ajax({
type: "POST",
url: targetPage,
data: dataText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
catch (err)
{
alert(err);
}
}
}
Example of user object
Object
BaseID: "fe85149c-71f2-4c61-b7c6-a00300e2f84e"
HasChanged: true
IsReferralReceived: false
IsReferralRequired: true
IsSeatApproved: true
Name: "Miles"
ReferralFromUser: null
ReferralFromUserID: null
ReferralReceivedBy: null
ReferralReceivedByUserID: null
ReferralReceivedOn: "/Date(-62135578800000)/"
RegisteredOn: "1330281960000"
SeatApprovedBy: null
SeatApprovedByUserID: null
SeatApprovedOn: "/Date(-62135578800000)/"
SeatNumber: "2"
SessionID: "d0773d5e-aeeb-4b9c-b606-0a564d6c5845"
UserID: "6af2fd9e-b4b6-4f5a-8e9c-fe7ec154d4e5"
__type: "SandboxClassRegistration.SessionUserField.ClientSessionUser"
C#
[WebMethod]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
Why does my JSON call never make it to the server? I've put a break point at the very beginning of the function (before the return) just so I can look at the jsonUser object parameter but it never makes it there.
All I get in return is this error:
POST http://localhost:60877/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser 500 (Internal Server Error)
--- UPDATE
Here is the final result (I had to "stringify" the object and then the final dataText being sent). The webservice method was unchanged
function CallWebServiceToUpdateSessionUser(target, user)
{
var dataText = { "jsonUser": JSON.stringify(user) };
$.ajax({
type: "POST",
url: target,
data: JSON.stringify(dataText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
I don't how much would help:
try change this
var dataText = { "jsonUser" : JSON.stringify(user) };
to
var dataText = JSON.stringify({ "jsonUser" : user });
I think you need to mark your service method as JASON enabled.
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
I realize this question was answered a while ago, but I had similar problem, and would like to provide some details on why OP's solution works
I assume the web service expects a string, which it will Deserialize and work with
In this case, calling JSON.stringify({"jsonUser": user}) does not convert user object to string, which will cause problems on the server.
When you call JSON.stringify({"jsonUser": JSON.stringify(user)}), your user oblect is converted to string with all quotes properly escaped.
Hope this helps someone in the future.
Here's the fiddle to illustrate http://jsfiddle.net/dvwCg/2/ :
HTML
<h1>webservice breaks</h1>
<span id="s1"></span>
<h1>webservice works</h1>
<span id="s2"></span>
JS
var jsonObject = {"a":1, "b":[{"x":"test", "y":12}, {"x":"test2", "y":120}]};
$("#s1").text(JSON.stringify({"d" : jsonObject}));
$("#s2").text(JSON.stringify({"d" : JSON.stringify(jsonObject)}));
p.s.
https://stackoverflow.com/a/6323528/3661 has a lot of useful info as well.

unable to pass post value over from ajax to the page in .net c#

Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];

Not all parameters get sent in jquery ajax call

I have a strange error where my jquery ajax request doesn't submit all the parameters.
$.ajax({
url: "/ajax/doAssignTask",
type: 'GET',
contentType: "application/json",
data: {
"just_a_task": just_a_task,
"fb_post_date": fb_post_date,
"task_fb_postId": task_fb_postId,
"sedia_task_guid": sedia_task_guid,
"itemGuid": itemGuid,
"itemType": itemType,
"taskName": taskName,
"assignedToUserGuid": assignedToUserGuid,
"taskDescription": taskDescription
},
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
But using firebug (and debugging) I can see that only these variables are posted:
assignedToUserGuid
itemGuid
itemType
just_a_task
taskDescription
taskName
It's missing fb_post_date, task_fb_postId, and sedia_task_guid
I have no idea what would cause it to post only some items and not others? Anyone know?
Data is sent to asp.net controller that returns jsonresult (hence the contentType)
Any help is appreciated. Thanks!
You could try some things such as:
See if all variables have values
Try to remove the "_" from the variable's names
What you should to to help with coding and debug is move the JSON data to a variable... ie, then you can easily see what is inside the variable before posting
var myData = {
just_a_task: just_a_task,
fb_post_date: fb_post_date,
task_fb_postId: task_fb_postId,
sedia_task_guid: sedia_task_guid,
itemGuid: itemGuid,
itemType: itemType,
taskName: taskName,
assignedToUserGuid: assignedToUserGuid,
taskDescription: taskDescription
};
var jsonData = $.toJSON(myData);
$.ajax({
url: "/ajax/doAssignTask",
type: "GET",
contentType: "application/json",
dataType: "json",
data: jsonData,
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
Though I dont have time to run the code, could be the speech marks in the JSON. That should be out as its native JavaScript
Check for special characters in your data values (, { } [ ] " '). You have to escape those characters for JSON to work.
Hope this helps.
in the interest of a sanity check, try adding a beforeSend to your options and ensure the values are being sent and go from there....
e.g.
.ajax({
beforeSend: function (xhr) {
// this==the options for this ajax request
if(! fb_post_date || !task_fb_postId || ! sedia_task_guid){
alert("BORKED!");
}
},
....

Categories