$.ajax({ url: "TestService.asmx/Test", data: "{'JSONData':'" + JSON.stringify(id) + "'}", // For empty input data use "{}", dataType: "json", type: "POST", contentType: "application/json", complete: function (jsondata, stat) { if (stat == "success") { var response = JSON.parse(jsondata.responseText).d; $("#divItem").html(response); } }, error: function (xhr, ajaxOptions, thrownError) { } });
Now the webservice method definition should look like:-
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string Test(string JSONData) { return JSONData + " Test Data"; }
Now that we have the code ready, lets try to run this. Oh No!! ASP.NET bounced back with following error.
"401 Unauthorized"
This internally means JQuery Ajax call had responded as System.InvalidOperationException and hence that would be thrown as 401 Unauthorized exception.
The simple solution is to include the following line before the class definition of the webservice
[System.Web.Script.Services.ScriptService]
“Real knowledge is to know the extent of one’s ignorance.”
– Confucius
I have this error, but when calling a webmethod in the code behind of the page. How would I go about implementing this solution without resorting to creating a webservice?
ReplyDeleteI've got many examples of this working perfectly well with the webmethod in the code behind, it's just on this one instance i get a 401. Very annoying.
Did you mean page methods ? as web methods are available only via web service.
ReplyDeleteI have been using ASP.NET Ajax webservices for years without any problems.
ReplyDeleteSince trying to implement $.ajax(), I consistently get the "401 Unauthorized" error in my dev workstation. Cannot get the jQuery.ajax syntax to work. It does work on my home workstation, but not on my Office machine. They have the same webservice files.
Have you used fiddler to see where the request is going to ? check your url: ~/TestService.asmx/Test"
ReplyDeleteGreat Article
ReplyDeleteASP.NET MVC Training
Online MVC Training
Online MVC Training India
Dot Net Training in Chennai
.Net Online Training
.net training online
Dot Net Online Training