Nicholas Barger
Nicholas Barger

Reputation: 363

Error with Ajax-Enabled WCF Service (JSON) when consuming from jquery .ajax()

Unfortunately it only hits the error condition when calling .ajax() and textStatus (2nd param) only says "error". I've read through several examples and other questions on stackoverflow but must be missing something. Thanks in advance for any help.

WCF Service:

[ServiceContract(Namespace = "http://localhost/")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Items
{
    [OperationContract]
    [WebGet]
    public string HelloWorld()
    {
        return "Hello World.";
    }
}

WCF Web.config

Pertinent parts only... Services:

<services>
  <service name="OService.ReadServices.Items">
    <endpoint address="soap" binding="basicHttpBinding" contract="OService.ReadServices.Items"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="OService.ReadServices.Items"/>
  </service>
</services>

Behaviors:

<endpointBehaviors>
    <behavior name="jsonBehavior">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>

Jquery

$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost/OService/ReadServices/Items.svc/json/HelloWorld",
        data: "{}",
        dataType: "json",
        success: function (msg) {
            alert("success: " + msg.d);
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("error: " + textStatus + " - " + errorThrown + " - " + xhr);
        }
    });
});

Upvotes: 0

Views: 769

Answers (1)

jocey
jocey

Reputation: 252

This reply is kind of late, but you defined your web method as a [WebGet] but call it as a POST request in your Jquery Ajax method. Replace the [WebGet] with something like:

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)].

Upvotes: 2

Related Questions