Cannot use ASP.NET web service from jQuery

Here's an interesting problem:

I have jQuery that looks like this:

$(document).ready(function() { $.ajax({ type: "POST", url: "http://localhost:63056/Service1.asmx/PrintOrderRecieptXml", data: {"CouponCode":"TESTCODE","Subtotal":14.2600,"ShippingTotal":7.5000,"TaxTotal":0.0000,"GrandTotal":21.7600,"OrderItemCollection":[{"Total":14.2600,"Qty":250}]}, dataType: "json", contentType: "application/json", error: function(xhr, msg) { alert(xhr.statusText); } });}); 

Now the problem is that it is sending the request, but the web service is not processing it correctly. In IE, I get a warning window "Internal Server Error" and with FireFox I get a warning window with nothing in it.

The strange thing is that when I use IE, I don't get an error message in the event log, but with firefox I get (bonus points for figuring out why this is):

"Exception message: Request format not recognized for URL unexpectedly ending in '/ PrintOrderRecieptXml"

I poked around some and found out that sometimes you need to add:

 <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost" /> <add name="HttpPostLocalhost"/> </protocols> </webServices> 

In your Web.Config, which I did, but that did not help. Interestingly, the web service works fine with SOAP or sends a query string, but not with JSON.

Any ideas?

+4
source share
3 answers

You need to specify your contribution to the data property as a JSON string, and not as an object:

 $(document).ready(function() { $.ajax({ type: "POST", url: "http://localhost:63056/Service1.asmx/PrintOrderRecieptXml", data: '{"CouponCode":"TESTCODE","Subtotal":14.2600,"ShippingTotal":7.5000,"TaxTotal":0.0000,"GrandTotal":21.7600,"OrderItemCollection":[{"Total":14.2600,"Qty":250}]}', dataType: "json", contentType: "application/json", error: function(xhr, msg) { alert(xhr.statusText); } });}); 

Using jQuery to use ASP.NET JSON Web Services has a good explanation of the requirements when talking to ASP.Net web services.

+8
source

Douglas is right - you need to format the data as a string. Be sure to read all the blog posts to which he has linked you. Encosia is a great resource for Ajax and Asp.Net.

+3
source

asp.net webservices do not return json normally. look here: JSON WebService in ASP.NET

+1
source

All Articles