How to display status description in AJAX? - asp.net

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.

Related

AJAX results in either a unexpected end of input error or an internal server error

I'm currently creating an ASP.NET MVC project, and my AJAX script is causing errors. I apologize for posting such a specific question, but I have honestly been stuck here for days.
$.ajax({
url: "/Home/Update/", //this calls a method in my controller to update the database.
data: JSON.stringify('{ "ToUpdate" : "1", "ID" : "#variableWithinCode" }'),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(errorThrown);
},
success: function(response){
//code here never executes as error is always thrown.
}
});
My Controller currently is of type ActionResult and returns the View. However, I have also tried returning nothing (void) and returning a JsonResult. Neither of these changes resulted in no errors.
Please could someone push me in the right direction, my Console has no errors. Any help would be greatly, greatly appreciated.
You can almost always use the simpler $.post helper (which wraps $.ajax), rather than $.ajax directly. Here's your code, updated to use $.post:
$.post('#Url.Action("Update", "Home")',
{
ToUpdate : "1",
ID : "#variableWithinCode"
})
.done(function(response, textStatus, jqXHR){
console.log(response);
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
});
You can also use the Url helper to inject the URL into your Javascript, assuming this code is in a <script> tag in a view.
In response to your comment:
It sounds like you're using this code within an event handler for a "button" of some sort. If that's the case, you'll want to capture the "this" context outside the ajax call, like so:
$('some-selector').on('click', function(e){
var _this = $(this);
$.post('#Url.Action("Update", "Home")',
{
ToUpdate : "1",
ID : "#variableWithinCode"
})
.done(function(response, textStatus, jqXHR){
_this.find('i').toggleClass('glyphicon glyphicon-chevron-up').toggleClass('glyphicon glyphicon-down');
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
});
});

stack trace if i use ajax(jquery)

Stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.
How can i obtain stack trace if i use ajax(jquery) to access to it.
function loadCompFilterTreeInfo() {
var d = "";
$.ajax({
type: "GET",
async: false,
url: '<%=HandlerUrl%>',
dataType: "json",
data: {},
success: function (data) {
d = data;
},
error: function (e) {
alert('<%= Resources.Resource.ErrorRequestingDataFromServer%>');
}
});
return d;
};
In my case occurs alert.
So you have two layers that are interacting with each other
Client
Server
Your Javascript code runs on the client-side, but it's making an AJAX call to a resource that is on the server-side of things.
In this situation, if you are getting an error, it's because the server has encountered an error with processing the request. If the server throws the error, you should be able to catch the error and display it in your 'error' event:
error: function(jqXHR jqXHR, String textStatus, String errorThrown) {
alert('Error Thrown: ' + errorThrown);
}
Also, assuming you have some sort of error logging on the server, you can check your server-side error log for any errors that may have occurred.

unable to get correct status code in AJAX Error handler

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.

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