Using jQuery with custom Web services in SharePoint

I had an requirement of using  jQuery for fetching data from my custom web service. The approach was adopted to have better UI experience,

So the user doesn’t feel the post back and flickering of screens.

I faced lot of issues to make it work, with all the note points found by goggling J made it work like charm.

The approach as follows

Step 1. Create a web service

Step 2. Client Side JavaScript definition to consume the web service

Step 1: Create web service

We will create a custom web service with a web method HelloWorld that takes a name as parameter and returns back a string in JSON format.

JSONJava Script Object Notation more info

It’s the same as C# objects. Object.Property to access the value.

Create a new web service project in ASP.NET and the web service definition as follows

namespace WebService1

{

    using System.ComponentModel;

    using System.Web.Services;

    using System.Web.Script.Services;

    using System.Web.Script.Serialization;

    ///<summary>

    /// Summary description for Service1

    ///</summary>

    [WebService(Namespace = http://tempuri.org/)]

    [ScriptService]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [ToolboxItem(false)]

    public class Service1 : System.Web.Services.WebService

    {

        ///<summary>

        /// Hello world

        ///</summary>

        ///<param name=”name”>Name</param>

        ///<returns>Hello name</returns>

        [WebMethod]

        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string HelloWorld(string name)

        {

            responseObject = new

                {

                    MyName = “Hello “ + name

                };

            return new JavaScriptSerializer().Serialize(responseObject);

        }

    }

}

Note:

ü  [ScriptService] to be added to allow calls from java script

ü  [ScriptMethod(ResponseFormat = ResponseFormat.Json)] over the method definition to return JSON

SharePoint context

Deploy the web service to the 12 hive folder to be accessible for any user regardless of the permission rights.

The following handler has to be added to the web.config in the layouts folder to avoid the 500 internal server error that will occur when you call the service from jQuery.

<httphandlers>

    <add verb=”*” path=”*.asmx” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory,

System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />

</httphandlers>

Step 2: Client Side JavaScript definition

jQuery AJAX calls are very simple to use compared to the native AJAX calls.  The call is made in jQuery by calling the function with required parameters.

var Name=“Balaji”;

var servicePath = “/_layouts/1033/myservice/Service1.asmx”;

//the current site url + service url

var serviceURL = location.href.substring(0, location.href.lastIndexOf(‘/’)) + servicePath;

$.ajax({

        type: “POST”,

        contentType: “application/json; charset=utf-8”,

        url: serviceURL + “/HelloWorld”,

        data: ‘{“name”:”‘ + Name + ‘”}’,

        dataType: “json”,

        success: processResult,

        error: failure,

        crossDomain: true

    });

 

//Handle result

function processResult(xData) {

    var responseObject = jQuery.parseJSON(xData.d);

    alert(responseObject.MyName);

}

 

//Handle Failure

function failure(){

         alert(“Error occurred”);

}

Note:

ü  contentType and dataType to be defined as JSON

ü  crossDomain is set to true when you make cross domain queries like your app runs in a different domain and the service runs in another domain.

ü  The parameter passed to the webservice is case sensitive and the format should be JSON.

The parameter “name” in the web method HelloWorld is the same in the jQuery call “data” attribute.

data: ‘{“name”:”‘ + Name + ‘”}’

Hope this kick starts.

2 thoughts on “Using jQuery with custom Web services in SharePoint

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