SharePoint REST Service ListData.svc and JQuery

This is a sample code on JQuery how you can retrieve a value from a SP 2010 REST service and display it in a HTML element.

In this case this is a piece of code that was used with a blog post xsl output.

There are 3 parts in this code:

1.  Find out the relative URL of the site in the current SP site

var location = window.location.pathname;
location = location.replace(“Lists/Posts/Post.aspx”, “”);

2.  Make a ajax call to the “ListData.svc” service. In this example “Posts” is the name of the posts library in a Blog site. The GetQueryStringParams is a JS function that retrieves the post (list item) ID to be passed to the service and the “LikesCounter” is the field which value we want to get.
$j.ajax({
type: “GET”,
url: location + “/_vti_bin/ListData.svc/Posts(” + GetQueryStringParams(“ID”) + “)/LikesCounter”,
dataType: “xml”,
success: parseXmlLikesCounter
});

URL Samle for the AJAX call:

http://servername:222/support/news/_vti_bin/ListData.svc/Posts(3)/LikesCounter

3. Take the value from the service. Strip it of any additional XML elements and get the value. In this case the single value is going to contain some extra XML defining the type of the data etc. I did not need that so I stripped any extra info and kept only the data from the field.
function parseXmlLikesCounter(xml) {
$j(xml).find(“Counter”).each(function () {

$j(“#ILikeItButtonValue”).text($j(this).text());
});
}

XML Samle of the response from the service:

<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes” ?>
<LikesCounter p1:type=”Edm.Double” xmlns:p1=”http://schemas.microsoft.com/ado/2007/08/dataservices/metadata&#8221; xmlns=”http://schemas.microsoft.com/ado/2007/08/dataservices”>1</LikesCounter&gt;

More info on the REST service in SharePoint:

http://msdn.microsoft.com/en-us/library/ff798339.aspx

Advertisements

One thought on “SharePoint REST Service ListData.svc and JQuery

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