SharePoint WCF WebService Post Example with JQuery Response

WCF Operation Contract

[OperationContract]
[WebInvoke(Method="POST", UriTemplate = "/AddNumbers", ResponseFormat= WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle= WebMessageBodyStyle.WrappedRequest)]
int AddNumbers(int n1, int n2);

Interface Implementation

public int AddNumbers(int n1, int n2)
{
    return n1 + n2;
}

JQuery .ajax request

function AddThis()
{
    $.ajax(L_Menu_BaseUrl + "/_vti_bin/myServices.svc/AddNumbers",
        {type: "POST",
            data: JSON.stringify({ n1: 2, n2: 9 }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {alert("Success: " + data),
error: function (XMLHttpRequest, textStatus, errorThrown) { alert("error: " + textStatus + errorThrown + XMLHttpRequest);}
     });
} 

$('#AddMe').click(function () { AddThis(); });

 

 

Author: Travis Gneiting

Passionate Professional .NET Developer