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.
Related
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.
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.
I have the following Webmethod in my C#/.NET web-application, file lite_host.aspx.cs:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result;
}
It should get the values of "accessCode" and "newURL" from a JavaScript function via a jQuery AJAX call with and make the appropriate changes in Cache:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However when I call the sendUpdate() function, I my script ends on $.ajax error and I'm getting an alert text "undefined".
Undefined means that msg.d doesn't exist. Try doing a console.log(msg) and use Chrome's debugger to see what is outputted (yeah, I know) to the console.
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.