unable to get correct status code in AJAX Error handler - asp.net

I am not able to get correct error code in the error handler of AJAX request. Everytime the error occurs, it returns me statusCode = 500. I tried to set it explicitly in my service as HttpContext.Current.Response.StatusCode = 403;, but still it gives me status = 500.
This is how my AJAX request looks like:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json"
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' + //This is always 500.
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
What am i missing here?

Looks like you were almost there, here is an example [WebMethod] that would throw a StatusCode 403.
[WebMethod]
public static string HelloWorld(string name)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 403;
return null;
}
Here is the calling jQuery Code.
$(document).ready(function ()
{
var jsonRequest = { name: "Zach Hunter" };
$.ajax({
type: 'POST',
url: 'Demo.aspx/HelloWorld',
data: JSON.stringify(jsonRequest),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, text)
{
$('#results').html(data.d);
},
error: function (request, status, error)
{
$('#results').html('Status Code: ' + request.status);
}
});
});
If you don't return a value as specified in your method signature you'll get a status code 500 returned.

According to the documentation:
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
So change your code to something more like this:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json",
error: ajaxFailed (jqXHR, textStatus, errorThrown)
});
function ajaxFailed(jqXHR, textStatus, errorThrown) {
alert(errorThrown + ' \n\r ' + textStatusText);
}
You might also find this answer provides some additional info.

Related

Passing multiple parameters with Ajax

I have a function in my .aspx page where I collect the first name and last name from the user and would like it to pass back to the server side code(c#). Ajax is being used and runs fine when one parameter is passed, although when a second parameter is passed I receive an error : can someone shed a little light, thanks
ERROR:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
POST http://ingleParam.aspx/GetCurrentTime 500 (Internal Server Error) jquery-.11.1.min.js:4
send jquery-1.11.1.min.js:4
m.extend.ajax jquery-1.11.1.min.js:4
ShowCurrentTime SingleParam.aspx:12
onclick
.ASPX Code
function ShowCurrentTime() {
$.ajax({
type: "Post",
url: "SingleParam.aspx/GetCurrentTime",
data: { name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Server Side Code:
[WebMethod]
public static string GetCurrentTime(string name, string lastname) {
return "Hello " + name + Environment.NewLine + "The current time is " + DateTime.Now.ToString();
}
I've had issues with sending json objects to webmethods. I've had success when I stringify the data being sent across. Like so:
data: JSON.stringify({name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val()}),
Give that a try and see if it helps.

javascript post 500 serrver internal error

i'm using ajax and web methods and when i execute this code appear an error thar say
post POST 500 (Internal Server Error)
but this path Exist!!!
this code is i'm using in this moment
function fnSendID() {
$.ajax({
type: "POST",
url: "GMap.aspx/SendCommands",
data: '{IDMobile: "'+$("#<%=Ddl_MobileCustomer.ClientID%>").val()+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Entro : " + response.d);
},
failure: function (response) {
console.log("Fallo : " + response.d);
}
});
<WebMethod()> _
Public Shared Function SendCommands(ByVal IDMobile As String) As String
'iIDMobile = GetMobileID(iIDMobile)
Dim sResponse As String = IDMobile + "Buenas"
Return sResponse
End Function
A 500 means the path you are hitting caused an error on the server side not that the path doesn't exist.
Debug the code and set a breakpoint at Dim sResponse As String = IDMobile + "Buenas".
Does it reach here? Is there any exception before the return?

How to display status description in AJAX?

I have a page that saves data using jQuery AJAX. On the server side, if the saving process fails, I want to set the StatusDescription of the Response object to "Hey this is Patrick!". The problem is, I can't display the StatusDescription on the client side! It always give me "Internal Server Error". How can I display my custom error message?
Save.ashx
Catch ex As Exception
Transaction.Rollback()
context.Response.StatusCode = 500
context.Response.StatusDescription = "Hey this is Patrick!"
End Try
AJAX
$.ajax
({
type: 'POST',
url: 'Save.ashx',
data: data,
async: false,
success: function(Data, TextStatus, XHR) {
alert(Data);
},
error: function(XHR, TextStatus, ErrorThrown) {
alert(ErrorThrown);
}
});
use XHR.responseText and then see what is the error.
Here is a good link regarding the error of jQuery Call
jQuery Ajax error handling, show custom exception messages
$.ajax
({
type: 'POST',
url: 'Save.ashx',
data: data,
async: false,
success: function(Data, TextStatus, XHR) {
alert(Data);
},
error: function(XHR, TextStatus, ErrorThrown) {
alert(XHR.responseText);
}
});
Instead I would return a string message in the response form the server and then you can use it in your error function.

Error response from jQuery ajax to asp.net WebService, but there's no error

I have an ajax query which calls a WebService. It works and does its thing, and returns nothing at all (it's a void). No errors in the application while debugging. But the error event for jquery .ajax keeps firing. textStatus and errorThrown are undefined. XMLHttpRequest has no indication of an error state.
Why does this query think it is getting an error response?
Also odd: if I put breakpoints in the WebMethod, the error gets thrown at the client BEFORE the method finishes. It does not seem to wait for it to finish, it just goes right to the error event. I expect this has something to do with the problem here...
$.ajax({
url: baseUrl() + "/webservices/usersetting.asmx/SetSetting",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: $.toJSON(ajaxData),
success: function (data) {
alert('success');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown + " data: " + ajaxData.id);
}
});
When debugging in the error event:
XMLHttpRequest
abort: function (){w&&Function.prototype.call.call(g,w);L("abort")}
onabort: null
onerror: null
onload: null
onloadstart: null
onprogress: null
onreadystatechange: function (){}
readyState: 4
response: ""
responseText: ""
responseType: ""
responseXML: null
status: 0
statusText: ""
upload: XMLHttpRequestUpload
withCredentials: false
__proto__: XMLHttpRequest
Here is the method. I tried it with void return, and "true". Tried responseformat Xml and Json. No difference.
[WebMethod(EnableSession = true),
ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public string SetSetting(List<UserSettingData> data)
{
UserSettingManager setMgr = new UserSettingManager(Global.UserSession.UserID);
foreach (UserSettingData item in data)
{
setMgr.SetSetting(item.name, item.value);
}
return (jsonString(true));
}
Issue resolved after Visual Studio restarted. No idea why but done and done.

why does [XMLHttpReequest] Message come?

I am calling below javascript/ajax page method from code behind, then
why does [XMLHttpReequest] Message come?
var options = {
type: "POST",
url: "Test.aspx/SendMessage",
data: "{'toMailAddress':'" + val + "','rno':'" + rno+ "', 'nonrno':'" + nonrno+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var val1 = response.d;
alert(val1);
if (val1 == "1") {
// Below code is used to close the window, if message has been sent to the user sucessfully.
var windowObj = window.self;
windowObj.opener = window.self;
windowObj.close();
}
},
error: function (result) {
alert("Error in " + result);
}
};
$.ajax(options);
I expect the message you are in fact seeing is "Error in XMLHttpRequest". This is what you would see if an error occurred during the call, because you have the wrong arguments for the error call back.
The method signature for the jQuery ajax error callback is:
error(XMLHttpRequest, textStatus, errorThrown)
So your error alert is being passed the XMLHttpRequest object, which is probably not what you meant to do. The code implicitly calls the toString() method on the XMLHttpRequest which will return "[object XMLHttpRequest]".
If that message isn't coming from the error callback, then there must be another bit of code somewhere passing the XMLHttpRequest object to alert(). I suggest you set a break point after your own alert() and single step through to see where the other alert() is.

Resources