Jquery Ajax call to webservice is failing - asp.net

Can anyone help? I have an issue with calling a asp.net webservice from jquery.. actually i think it maybe jquery ... as i have a break point and it doesn't arrive in the webservice..
Here is my jquery, the webservice method accepts 2 parameters...
So i setup a simple test to pass in 7 and 7 .. i tried replacing with the word "test" also and it doesn't work..
Basically lands in the error function which displays "sorry error happens" but the err is undefined.
jQuery.ajax({
type: 'POST'
, url: 'CallService.asmx/TempCanMakeCall'
, contentType: 'application/json; charset=utf-8'
, dataType: "json"
, data: "{'reservationNum':'7','completedReservationNum':'7'}"
, success: function(data, status) {
alert(data);
}
, error: function(xmlHttpRequest, status, err) {
alert('Sorry! Error happens.' + err);
}
}
);
Here is the asp.net webservice
[WebMethod()]
public bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}

xmlHttpRequest.responseText has always been my goto when dealing with jQuery AJAX errors.
Try making your ASP.NET function static:
[WebMethod()]
public static bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
Also note that the returned JSON value is encapsulated in an object named 'd' (ASP.NET specific.) To display your return value upon success, you would need to do this:
success: function(data, status) {
alert(data.d);
}

The jquery ajax call looks fine. I think you need to make sure that the path to "CallService.asmx" is correct. The way it is now, I will only work if the file making the jQuery call is in the same virtual directory as the ASMX.

In your error callback function, you could check 'xmlHttpRequest.status' to get the http code returned from the server. This may give you another clue. If ichiban above is correct, it should be a 404.

You can check the xmlHttpRequest.responseText property. The response text is very probably an html document returned by the server that contains the reason for the error.
If you are using Visual Studio, you can also enable script debugging in Internet Explorer and put the following keyword in your error function: debugger. The browser sees this as a breakpoint and will invoke a debugger (which should be Visual Studio). Now you can check the entire contents of the xmlHttpRequest instance.
For clarity, your error function will then look like this:
function(xmlHttpRequest, status, err)
{
debugger;
...rest of your function...
}

Related

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

How does Angular know there was an error on an $http request?

How does the $http function of Angular "know" the response was an error in an ASP.NET request? I'm looking at the response headers but don't see anything that looks relevant.
I have this service in Angular:
service.getStuff = function () {
return $http({
method: 'GET',
url: './GetJsonData.aspx?RequestType=Stuff'
//That asp.net page returns json on success, but a regular
//asp.net error page on failure. I know there's better ways,
//but ignore that, that's not the question here.
});
}
and I use it like this:
$scope.reloadData = function () {
MyService.getStuff().success(function (response) {
alert("good");
})
.error(function (response) {
alert("bad");
});
};
That asp.net page is (correctly) throwing an exception on bad input and angular is (correctly) recognizing it as an error. But I can't figure out it knows there was an error. Is there some header that's it looking for? In the success case I receive json and in the failure case i receieve HTML, so as a human; but the angular code doesn't know that. So how is it recognizing this was an error?
It uses the HTTP status codes. This is standard behavior for restful clients and services.

Data not being sent to the server through web method?

I use PageMethods to return parameters from the client-side to the server-side. Something like this:
if (/*node has no kids*/) {
PageMethods.ApplicationInfo(node.data.key, node.data.title, onSuccess, onFailed);
<%=Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument") %>
}
else {
PageMethods.ApplicationInfo(0, "", onSuccess, onFailed);
}
My web method:
[WebMethod(EnableSession = true)]
public static void ApplicationInfo(int appId, string appDescr)
{
curAppId = appId;
curAppDescription = appDescr;
}
As you can see, I invoke a postback if the condition is true.
So, the problem is the web method runs smoothly and ends in onSuccess function in the 'else' condition, but gives me the 'server method failed' error otherwise.
What can cause it? Thanks a lot in advance!
EDIT
Ok problem changed.
I moved the postback to the onSuccess function, and stopped getting the mistake.
Locally, everything works fine, but the data which I pass to ApplicationInfo somehow are not passed, when I try to launch the site from the server.
What can be the problem?

jsonp cross domain only working in IE

EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE
I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..."
Any ideas?
Here is the code:
$.ajax({
type: "POST",
url: "http://test/TestService.asmx/HelloWorld?jsonp=?",
dataType: "jsonp",
success: function(data) {
alert(data.prop1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown);
}
});
And the server code is:
[ScriptService]
public class TestService : System.Web.Services.WebService{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
string jsoncallback = HttpContext.Current.Request["jsonp"];
var response = string.Format("{0}({1});", jsoncallback, #"{'prop1' : '" + DateTime.Now.ToString() + "'}");
HttpContext.Current.Response.Write(response);
}
}
Glad it's working now.
You're trying to send the parameter, "jsonp" -- that you need to pass for the "padding" part of the json -- as a GET parameter, i.e. in the URL string. Which is the right thing to do.
But because you've specified POST, that's not happening. Effectively, because you're specifying POST, the server is expecting all the parameters to be in the POSTed data, not in GET variables, so it's not checking the URL to retrieve the parameter.
I think it's possible that jQuery is being quite forgiving/smart about how it's doing the JSON evaluation, and therefore still working in IE, because (a) if the server doesn't read the "jsonp" variable, I think it'll send back "({'prop1' : '<today's date>'})", which is still evaluate-able as JSON, and (b) IE doesn't have the same restrictions on cross-site scripting ("same origin" policy) as the other browsers. But I'd need to debug it to be sure.
I'd suggest using FireBug in Firefox to debug what's going on with this sort of request in the future, but the main take-away is that if you're sending parameters as part of the URL, use GET, not POST.
Cheers,
Matt
Unless you specify the jsonp and/or the jsonpCallback option, jQuery auto-generates the function name for you, and adds a query param like callback=jsonp1272468155143. Which means your application needs to output using that function name.
You can always set jsonpCallback to test, in which case your example would work.

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

Resources