Wednesday, August 22, 2012

JQuery and SPServices


JQuery and SPServices    

‘Sup All…I’m going to be covering the use of JQuery and SPServices in this article.  JQuery is a library of cool JavaScript functions you can use to make your websites more dynamic. SPServices is a set of JQuery tools specifically designed to work with SharePoint web services.

JQuery
You can download JQuery here.  It is highly suggested by SharePoint gurus smarter than I on the subject of JQuery and SharePoint that you upload your JQuery file into a SharePoint library.  I, cleverly, named mine jsandjquerystuff, and placed my JQuery in there.  What is further suggested is that you give it a common name, regardless of the version, so that you don’t have to worry about subsequent versions.  You can keep track of versions in the comments field.  Here is what mine looks like:

I keep both the JQuery library and the JQuery.SPServices in this library so they are easy to refer to on my SharePoint pages.                                                                                                                                                                                                                                                        

SPServices


As I mentioned earlier, SPServices is a special set of library’s in JQuery that allow you to utilize the SharePoint web services for functions like getListItems, getListView, getCollection, etc.  Basically any service offered by SharePoint web services is available in SPServices.  It can be downloaded here.

Our Mission


The application I will be sharing will provide a Help page for new users, by providing a list of blog entries based on their level of interest.  There will be three levels:

  • Getting Started
  • What the Heck?
  • All Blogs

A simple intro to JQuery


I downloaded relevant animated gifs from animationfactory.com.


A little “coolness”


I didn’t want to just present the user with the three options.  So I created a “Click to Start!” button that makes the three guys magically appear.  The code for that follows:

I first place my references to the JQuery and SPServices libraries within <script> tags within my <head> tags as seen below:




I placed my <div> tags in the style section so that I could hide my three guys (see display:none).  Then in the first portion of my <body> tag I placed the “Click to Start!” button and the <div> tags that hold my three guys and placed three buttons next to them:






Now you see them…Now you don’t


When the user first opens the page they will simply see the “Click to Start” button.  When they click the button the three guys appear.  If they click it again, they disappear.  Here is the very simple code that allows this to happen.



As you can see, the document object model is in full affect here.  Every tag or ID is in play and can be used by JQuery.  In the code above the $(“StartHere”).click refers to the button tag with the ID “StartHere”.  What is happening in the IF statement is pretty simple.  If the DIV tags are hidden, make them visible. If not, make hide them.  SlideDown is a function in JQuery that gives the effect of sliding down and has the optional speeds of “Fast” or “Slow” or you can specify your own speed value in milliseconds.

I’ll show you mine…

Now, things get a little trickier here.  We need to add functionality to the buttons that will:

  • Display a list of ALL blog topics
  • Display a list of blog topics that are strictly for beginners
  • Display a list of blog topics that address troubleshooting topics

For this we will need to query the blog entries.  We will have to use Collaborative Application Markup Language (CAML) for this purpose.  An intro to CAML is beyond the scope of this article, but Mark Ackley has a great article that will give you a good intro.  In short, we will create an OnClick event for each button that will create the query and then call the function to run the query.






In the code above the CAML query is pretty simple.  I’ll be querying the entries from a blog post.  Blog posts are simply lists in SharePoint.   So here is a breakdown of what I did:

$("#GettingStarted").click(function()
                {
                $("tr").remove();    //remove all table rows
                var query = "<Query>" +
                        "<Where>" +
                            "<Eq>" +
                                "<FieldRef Name='PostCategory'/><Value Type='Lookup'>Getting Started</Value>" +
                            "</Eq>" +
                        "</Where>" +
                        "<OrderBy>" +
                            "<FieldRef Name='PostCategory'/>" +
                        "</OrderBy>" +
                        "</Query>";
                         GetTopics(query);                                                 
                 });
CAML queries are like a YODA version of SQL Queries.  They backwards seem.
This WHERE clause would be:
 Select * from Post where PostCategory = “Getting Started” ORDER BY PostCategory
You don’t have to specify the name of the list here in the query for reasons you will see later.
I then run the GetTopics function, passing the newly created query value, which actually runs the query along with making the call to the SharePoint web service.
I repeat the process for the other buttons.


GetTopics Function



We are going to run the “GetListItems” web service, so we build the service parameters prior to executing the service.
Method=”GetListItems”
myWebURL=[location of the list]
list=[name of the list]
fieldsToRead=[fields from the list that you want to read]
Now, for the SPServices function we specify the:
Operation-the service to be called
webURL-the locaton of the list
listName-the name of the list
CAMLViewFields-the fields from the list that you want to read
CAMLQuery-the query to be executed on the data returned
xData is the object returned
Status is the status returned by the operation (Success or Error)
For each row returned by the query capture the Title, Category and  Date Published. We use the ID field to build the hyperlink to access the blog entry and pass them to the AddRowToTable function which will append the row to a table we have defined outside of the script tags.


AddRowToTable Function


This function will use the hyperlink value we created in GetTopics and the name of the blog to display the list of topics.


PostTable





The $(“#postTable”).append function will add rows to this table.


Tada!

Now, when users click on the buttons they are presented with a list of blog topics filtered by their need:










The Full Monty


Here is all the code that I used to get this working.  I may not be the most practical example, but it at least gets your feet wet in working with  JQuery and SPServices.  Also, you can use this as a template later for creating apps that require the same type of functionality.

<html dir="ltr">
<head runat="server">
<META name="WebPartPageExpansion" content="full">
<meta name="ProgId" content="SharePoint.WebPartPage.Document">
<style type="text/css">
div {
                display: none;
                float: left;
                border: medium black;
}
</style>
<!--My copy of jQuery -->
<script src="[your sharepoint site URL]/jsandjquerystuff/jquery.min.js" type="text/javascript"></script>
<!--My copy of SPServices -->
<script type="text/javascript" src="[your sharepoint site URL]/jsandjquerystuff/jquery.SPServices.min.js"></script>
</head>
<body>
                <button id="StartHere">Click to Start!</button>
                <div>
                                <img alt="" src="Ocelot%20Pics/bean_shoulder_shrug_hg_clr.gif" width="54" height="84">
                                <button id="GettingStarted" value="GettingStarted">Where Do I Start?
                                </button>
                </div>
                <div>
                                <img alt="" src="Ocelot%20Pics/stick_man_puzzled_sm_clr.gif" width="54" height="84">
                                <button id="What" value="What">What the...?</button>
                </div>  
                <div>
                                <img alt="" src="Ocelot%20Pics/geek_laptop_gif_md_clr.gif" width="54" height="84">
                                <button id="All" value="All">All Blogs!</button>
                </div>
                <script type="text/javascript">
                jQuery(document).ready(function($) {                  //READY
                                $("#StartHere").click(function ()               //Start here Button
                                                                {
                                                                                if ($("div:first").is(":hidden"))
                                                                                                {
                                                                                                                $("div").slideDown("slow");
                                                                                                }
                                                                                else
                                                                                                {
                                                                                                                $("div").hide("slow");
                                                                                                }                             
                                                                });                           //End Start Here Button
                });// End READY
               
                //If "Getting Started" is clicked, make up the query and run GetTopics to display the blog topics
                                        $("#GettingStarted").click(function()
                                        {
                                                $("tr").remove();                        //remove all table rows
                                                var query = "<Query>" +
                        "<Where>" +
                            "<Eq>" +
                                "<FieldRef Name='PostCategory'/><Value Type='Lookup'>Getting Started</Value>" +
                            "</Eq>" +
                        "</Where>" +
                        "<OrderBy>" +
                            "<FieldRef Name='PostCategory'/>" +
                        "</OrderBy>" +
                                    "</Query>";
                               GetTopics(query);                                                           
                 });
                //If "All Blogs" is clicked, make up the query and run GetTopics to display all of the blog topics
                                                $("#All").click(function()
                                        {
                                                    $("tr").remove();//remove all table rows
                var query = "<Query>" +
                        "<Where>" +
                            "<Neq>" +
                                "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
                            "</Neq>" +
                        "</Where>" +
                        "<OrderBy>" +
                            "<FieldRef Name='PostCategory'/>" +
                        "</OrderBy>" +
                    "</Query>";
                    GetTopics(query);
                                                                });
               
//If "What the..." is clicked, make up the query and run GetTopics to display the "What the Heck...?" blog topics
                                $("#What").click(function()
                                        {
                                                    $("tr").remove();//remove all table rows
                var query = "<Query>" +
                        "<Where>" +
                            "<Eq>" +
                                "<FieldRef Name='PostCategory'/><Value Type='Text'>What the Heck?</Value>" +
                            "</Eq>" +
                        "</Where>" +
                        "<OrderBy>" +
                            "<FieldRef Name='PostCategory'/>" +
                        "</OrderBy>" +
                    "</Query>";
                    GetTopics(query);
                                                                });
                                                //Function to execute queries based on button click
                                                function GetTopics(query)
                                                {//--Begin Function
                                        //The Web Service method we are calling, to read list items we use 'GetListItems'
                                        var method = "GetListItems";
                                        
                                        //The display name of the list we are reading data from
                                        var myWebURL = "http://[path to your SharePoint Blog/]";
                                        var list = "Posts";
                                        //We need to identify the fields we want to return.
                var fieldsToRead =     "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                "<FieldRef Name='PostCategory' />" +
                                "<FieldRef Name='PublishedDate' />" +
                            "</ViewFields>";
        //Here is our SPServices Call where we pass in the variables that we set above
        $().SPServices({
                                debug: true,
                operation: method,
                async: false,  //if you set this to true, you may get faster performance, but your order may not be accurate.
                webURL: myWebURL,
                listName: list,
                CAMLViewFields: fieldsToRead,
                  CAMLQuery: query,
                      //this basically means "do the following code when the call is complete"
                    completefunc: function (xData, Status)
                    {
                        //alert(".SPServices. Status =" + Status);
                        //this code iterates through every row of data returned from the web service call
                        $(xData.responseXML).SPFilterNode('z:row').each(function()
                       {
                            //here is where we are reading the field values and putting them in JavaScript variables
                            //notice that when we read a field value there is an "ows_" in front of the internal field name.
                            //this is a SharePoint Web Service quirk that you need to keep in mind.
                            //so to read a field it is ALWAYS $(this).attr("ows_<internal field name>");
                           
                            //get the title field
                            var name = ($(this).attr("ows_Title"));
                            //get the post
                            var post = ($(this).attr("ows_PostCategory"));
                            //get the publish date
                            var pubDate = ($(this).attr("ows_PublishedDate"));
                            var postURL = myWebURL + "/lists/posts/ViewPost.aspx?ID=" + ($(this).attr("ows_ID"));
                            //add the data from the row to the table on the screen
                            AddRowToTable(name,post,pubDate,postURL);
                           
                       });//End SPFilerNode
                    }//End  CompleteFunct
               });//--End SPServices
             
   } //End GetTopics
  
                    //Function to display data table
                                                                                function AddRowToTable(name,post,pubDate,postURL)
 {
$("#postTable").append("<tr align='left'><td><a href='" + postURL + "'>" + name + "</a></td></tr>");
}
</script>
<table id="postTable">
</table>
</body>
</html>


Hope you found this useful…


Your Humble Servant,


Vette

No comments: