Reputation: 549
I am trying to create a webservice that takes data, posts it to a database, and returns the result. I know how to write all the C# code that does that, but it is the communication that I am having problems with. At the moment, I am just trying to invoke the service and get back "Hello World" (I start with something simple since I have no idea what I'm doing)...
My Jquery:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert("Success");
$("#log").html(msg);
alert(msg);
}
});
My Webservice:
public class PersonService : System.Web.Services.WebService
{
~
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
~
}
After using chrome to Inspect the Element, and selecting the Network tab, finding my webservice, it shows me that the result was:
<?xml version="1.0" encoding="utf-8"?>
<string>Hello World</string>
So, it seems that the service executed successfully, but the success function does not fire, and there are no errors in the console. What is going on? Also, why is the result in XML?
Do I need to use Web Services, or could I just post the variables via AJAX to an ASPX page that would process it the same way it would a form submission?
Upvotes: 0
Views: 227
Reputation: 43097
Using jQuery to Consume ASP.NET JSON Web Services » Encosia
$(document).ready(function() {
$.ajax({
type: "POST",
url: "RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Hide the fake progress indicator graphic.
$('#RSSContent').removeClass('loading');
// Insert the returned HTML into the <div>.
$('#RSSContent').html(msg.d);
}
});
});
Also, you're missing [ScriptMethod] on your web service method and [ScriptService] on your service class.
[WebService]
[ScriptService]
public class PersonService : WebService
{
[ScriptMethod]
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
}
Upvotes: 2