So, you want to consume a WCF service from jQuery but didn’t know how? I didn’t either and dug around the internets for a while. I found a lot of information out there.
So I collated all the sources and put together an example which shows you all the info in one place and has the best practises incorporated as well.
Step 1: Create a website. I’ve used an ASP .NET MVC website to do this, but feel free to use your own.
Step 2: Create the WCF service. Here’s the code for mine.
namespace JsonWebService.ws
{
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
#if DEBUG
[ServiceBehavior
(IncludeExceptionDetailInFaults = true)]
#endif
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements
(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class JsonService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
public Emp DoWork()
{
// Add your operation implementation here
Emp obj = new Emp() { Age = 12, Name = "SomeName" };
return obj;
}
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
public Emp GetEmp(int age, string name)
{
Emp emp = new Emp();
if (age > 0)
emp.Age = 12 + age;
if (!string.IsNullOrEmpty(name))
emp.Name = "Server" + name;
return emp;
}
public class Emp
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
Step 3: Create a page and and setup some boiler plate HTML to display the data travelling to and from the WCF service.
<span id="lbl"></span>
<input type="button" value="ClickMe" onclick="javascript:ops.getEmp();" />
Step 4: Create the necessary JavaScript to make the AJAX calls. Read the inline comments!
//create a global javascript object for the AJAX defaults.
var ajaxDefaults = {};
ajaxDefaults.base = {
type: "POST",
timeout : 1000,
dataFilter: function (data) {
//see http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/
data = JSON.parse(data); //use the JSON2 library if you aren’t using FF3+, IE8, Safari 3/Google Chrome
return data.hasOwnProperty("d") ? data.d : data;
},
error: function (xhr) {
//see
if (!xhr) return;
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
//console.log works in FF + Firebug only, replace this code
if (response) console.log(response);
else console.log("Unknown server error");
}
}
};
ajaxDefaults.json = $.extend(ajaxDefaults.base, {
//see http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
contentType: "application/json; charset=utf-8",
dataType: "json"
});
var ops = {
baseUrl: "/ws/JsonService.svc/",
doWork: function () {
//see http://api.jquery.com/jQuery.extend/
var ajaxOptions = $.extend(ajaxDefaults.json, {
url: ops.baseUrl + "DoWork",
data: "{}",
success: function (msg) {
console.log("success");
console.log(typeof msg);
if (typeof msg !== "undefined") {
console.log(msg);
}
}
});
$.ajax(ajaxOptions);
return false;
},
getEmp: function () {
var ajaxOpts = $.extend(ajaxDefaults.json, {
url: ops.baseUrl + "GetEmp",
data: JSON.stringify({ age: 12, name: "NameName" }),
success: function (msg) {
$("span#lbl").html("age: " + msg.Age + "name:" + msg.Name);
}
});
$.ajax(ajaxOpts);
return false;
}
}
Step 5: You’re done! However, also go through the following blog posts to get a better understanding of what’s happening under the hood
http://www.west-wind.com/weblog/posts/324917.aspx
http://stephenwalther.com/blog/archive/2010/03/26/using-jquery-to-insert-a-new-database-record.aspx
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/