Consuming a JSON WCF Service with jQuery

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/

About these ads

3 Responses to “Consuming a JSON WCF Service with jQuery”

  1. ASP.NET MVC Archived Blog Posts, Page 1 Says:

    [...] to VoteConsuming a JSON WCF Service with jQuery (3/27/2010)Saturday, March 27, 2010 from meondotnet.wordpress.comStep 1: Create a website. I’ve used an ASP [...]

  2. Consuming a JSON WCF Service with jQuery (via Me Too on .NET) | Notes on Technology Says:

    [...] 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 servic … Read More [...]

  3. soni009 Says:

    [Moderator Comments] : I’ve posted a reply there

    Hi,
    I looked around for some code to do this and tried your sample.
    For some reason, I’m getting an error.
    Posted it on stackoverflow.
    Could you please take a look at it if possible?

    http://stackoverflow.com/questions/4979076/jquery-wcf-http-404-error

    Thanks
    Soni

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: