In my previous post I showed how to use the new SharePoint 2013 Restful API to pull data out of a list. While this new method can make some things easier, I haven’t found it to be as robust at times as the SPService library has been. Plus, doing work in SharePoint 2010 doesn’t allow us to capitalize on the new features. So how can we write one set of code that will work on both systems? The simple answer I have found is to rely on the SPServices library built on jQuery.

Under the hood SPServices is a JavaScript wrapper for the exposed SharePoint web service. All of the work we plan to do with the library we could write out ourselves but why do all of the heavy lifting ourselves if we don’t mind a little JavaScript overhead. You can download the library from their codeplex site: http://spservices.codeplex.com/
My personal practice is to upload the file to site assets folder of site collection I am working in. once this is done you just need to add the reference like we did with jquery.

Now that we have the library installed, we need to look at what we can do with it. The library documentation is decent but sometimes lacks good examples. We can find all of the list functions at http://spservices.codeplex.com/wikipage?title=Lists. The GetListItems operation is what we will be using. In the past, I would write a call directly to the SPServices function each time it was used, but I have found that most often I tend to build pages with multiple calls, thus I make a simple wrapper around the function that looks something like this:

For this example we are going to assume that we are still using our ‘Current Projects’ list but let’s assume our manager has created a custom view to filter the project data and now wants us to apply the filter to the output. We could just hard code the CAML code for the filtering but our manager has requested we use the view so that they can update the filtering without touching the code. We still want our output to be appended to a div with the ID=projectOutput.

So first we need to set up our variables to pass. The list name, the GUID of the view, the field names and our site url and call into our SPServices wrapper and get an xml document back.

Now we have to deal with the return data. First we should clear the output container to make sure that we don’t have a double post issue that can occur with some partial post backs retriggering a jQuery(document).ready. Once this is done we should make sure we got data back, otherwise output a friendly message.

Now we simply add in the string parsing. Remember that the fields coming back will have placed an ows_ at the beginning of each field name.

And that’s it. Here it is all put together.

 

This makes for some quick and easy work that we can then port between 2010 and 2013 servers whenever we need. Next time in Part 3 we will expand this example to allow for us to write our own CAML code to filter.

Like this post? Share it!