why does [XMLHttpReequest] Message come? - asp.net

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.

Related

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.

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.

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.

Calling Linq to SQL method in Web service with jQuery

I have a test web service called: MySimpleService.svc with a method called:GetUserNamesByInitials. below is the Linq to SQL code:
[OperationContract]
public static string GetUserNamesByInitials(string initials)
{
string result = "";
//obtain the data source
var testDB = new TestDBDataContext();
//create the query
var query = from c in testDB.TestTables
where c.initials == initials
select c;
//execute the query
foreach (var c in query)
{
result = result + c.full_name;
}
return result;
}
I have used that code in page behind and it works well. However when i try to call it using jQuery I don't get any result, no errors nothing. below is the code i use in jQuery:
$('#TextBox3').live('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
//call function here
$.ajax({
type: "POST",
url: "/MySimpleService.svc/GetUserNamesByInitials",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"word":"' + $('#TextBox3').val() + '"}',
success: function(data) {
$('#TextBox4').val(data.d);
}
});
}
});
});
what I do is to type the user id in one textbox (TextBox3) and when I press the Tab key the result is shown in another textbox (TextBox4).
The jQuery call works well with other methods that do not call the database, for example using this other web service method it works:
[OperationContract]
public string ParameterizedConnectionTest(string word)
{
return string.Format("You entered the word: {0}", word);
}
However with the Linq method it just does not work. Maybe i am doing something wrong? thank you in advance.
The web service is expecting a string named "initials" and you're sending it a string called "word". More than likely it is throwing an exception that it's not being passed the expected parameter.
Try adding an error: function() in your $.ajax() call to catch the error. I would also suggest installing FireBug or Fiddler to be able to view and debug the AJAX request and response. Here's the updated $.ajax() call with the right parameter name and an error function which should invoke your chosen javascript debugger if you have it open:
$.ajax({
type: "POST",
url: "/MySimpleService.svc/GetUserNamesByInitials",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"initials":"' + $('#TextBox3').val() + '"}',
success: function(data) {
$('#TextBox4').val(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
debugger; // Will let you see the response in FireBug, IE8 debugger, etc.
}
});
Update
So I just noticed that you're using WCF services instead of normal ASP.Net (ASMX) services... Some additional suggestions:
Enable IncludeExceptionDetailInFaults in your web.config so that you can debug any errors happening. ASP.Net services will return an error by default but you need to explicitly turn this on for WCF.
Try adding an additional attribute below your [OperationContract] attribute to specify you're expecting a post with JSON data:
[WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]

Resources