Thursday, July 12, 2012

Using jQuery with SharePoint 2010

jQuery is an open source JavaScript library that helps you build rich, dynamic, client-side applications. The power in jQuery comes from its simplicity and powerful query syntax. One of jQuery’s most powerful abilities is to quickly select various HTML DOM elements. Once you find the element or collection of elements, jQuery makes it easy to modify attributes and CSS for those elements. jQuery also supports extensibility through a rich plug-in model. In fact, a huge community of jQuery plug-ins is available. It is actually a core design point of jQuery to keep the core library small and provide most of the rich functionality via plug-ins. Although it is not possible to cover all aspects of jQuery in this chapter, there is one very important jQuery API with which SharePoint developers and designers should become familiar: the Ajax library. You learned about calling SharePoint from the client using the Client Object Model earlier in this chapter, but the Client Object Model doesn’t cover all SharePoint functionality. For example, Search is not covered by the Client Object Model and many others. The Client Object Model covers only APIs in theMicrosoft.SharePoint.dll. This is where the jQuery Ajax library comes into play. Fortunately, SharePoint covers almost all its functionality with SOAP-based .asmx web services. The Ajax library makes it relatively easy to call these web services using jQuery from the client.
In this section, you will see how to call SharePoint web services using jQuery and dynamically display the results in a Content Editor Web Part (CEWP), without writing any server code.

Loading jQuery

You can download the jQuery library from the jQuery homepage. The current version as of thiswriting is 1.4.2. The jQuery library is a single fi le called jquery-1.4.2.js. There are actually two versions of this file.
  • jquery-1.4.2.js — A human-readable source version.
  • jquery-1.4.2.min.js — A minified and condensed version
I recommend using the source version for development and the minified version in production. Download the jquery-1.4.2.js file and put it in somewhere on your SharePoint site. Create a Scripts folder under the SiteAssets library to hold your JavaScript files. The path would be something similar to http://intranet.contoso.com/SiteAssets/Scripts/jquery-1.4.2.js.
To add the jQuery library, use the following script tag on your page.
<script src="/SiteAssets/Scripts/jquery-1.4.2.js" type="text/javascript"></script>
Another option is to use the jQuery library hosted on Microsoft’s content delivery network (CDN). The CDN geographically distributes the fi le around the world, making it faster for clients to download the file. With SharePoint on-premise installations, such as your intranet, this is not as important, but with SharePoint Online or SharePoint-based Internet sites, this will increase the perceived performance of your site. Add the following script tag to your page to use the Microsoft CDN to load the jQuery library.
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"type="text/javascript"></script>
Ajax script loader
One thing that you need to be concerned with when using jQuery is that the jQuery library is loaded only once. There are a number of ways that you could do this, but this section mentions three ways and the various caveats associated with each method.
The first method is to just include the script tags, like you saw previously, directly to the page or, even better, to the master page. You would need to ensure that no other components also add a reference to the jQuery library. Here, the term "components" refer to anything that may inject code when the page renders, such as Web Parts. This is an acceptable approach if you control the entire page, but many times this is not possible due to the modular nature of SharePoint development.
The next approach is to use the ScriptLink control. The ScriptLink control ensures that the script is loaded only once and will also ensure that other dependencies have been loaded first. Add the following ScriptLink server-side tag to your page to load the jQuery library.
<SharePoint:ScriptLink ID= "SPScriptLink "
  runat= "server" Defer= "false "
  Localizable= "false " Name= "jquery-1.4.2.js ">
</SharePoint:ScriptLink>
The ScriptLink control requires that you put the jQuery library file in the LAYOUTS directory, C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS. This may not be possible if you have limited rights to the server, such as when you are creating sandboxed solutions. Also, even if the JavaScript library is in the LAYOUTS folder, theScriptLink control is not allowed to run as a sandboxed solution. Therefore, I do not recommend this approach.
The third method, and the one that you should use, is to load jQuery using the Microsoft Ajax script loader, or another client-side script loader. One thing to be aware of is that the Microsoft ASP.NET Ajax library is now included as part of the Ajax Control Toolkit. This means that the ASP.NET Ajax library was split into server controls, which are now in the Ajax Control Toolkit, and client code, which is now done using jQuery. So, most of the functionality that was provided is now done in jQuery or through a jQuery plug-in, except the script loader. The Ajax library script loader has not been released yet for jQuery, so you will need to use the existing Start.js script loader library until it is released.
Download the Start.js library to your Site Assets library’s Script folder that you created earlier to hold your scripts. You can find the current script loader on Microsoft’s CDN at the following URL.
http://ajax .microsoft.com/ajax/beta/0910/Start.js.
You should also download the source version for development from the following URL.
Alternatively, you could load the Start.js library directly from the Microsoft CDN.
There are two steps to loading the jQuery library, or any of your custom JavaScript libraries. First, reference the script loader on your page using the following script tag.
<script src= "/SiteAssets/Scripts/Start.debug.js " type= "text/javascript "></script>
Or, if you are loading the library from the CDN, use the following script tag instead.
<script src= "http://ajax.microsoft.com/ajax/beta/0911/Start.js "type= "text/javascript"></script>
The second step is to reference the jQuery library or your own libraries using the Sys.loadScripts method, which is part of the Start.js library. The Sys.loadScripts method takes an array of scripts to load and a callback function to call when they have been loaded. Add the follow code to load the jQuery library.
<script type= "text/javascript ">
  Sys.loadScripts(["/SiteAssets/Scripts/jquery-1.4.2.js "], function() {
    alert("jQuery Loaded ");
  });
</script>
The Ajax Script Loader prevents the jQuery library from being loaded multiple times on the same page, even if you add many Web Parts that are using this code.

Calling SharePoint web services with jQuery

You have seen how to get SharePoint list data using the Client Object Model, but there are many types of SharePoint data that are not covered by the Client Object Model. The Client Object Model applies only to data in the Microsoft.SharePoint.dll, essentially functionality found in SharePoint Foundation only. To leverage other SharePoint data, such as profile data or search data, you will need to call the SharePoint web services. Calling these web services from the client using JavaScript has become much easier using the jQuery Ajax API. Let’s first take a quick look at how to retrieve list data, in this case the Announcements list, using jQuery. You could do this using the Client Object Model, but this example should serve as a bridge from doing it with the Client Object Model to doing it with jQuery.
jQuery in the Content Editor web part
To keep things simple and demonstrate another technique for using JavaScript on your pages, you will use the Content Editor Web Part (CEWP) to display a list of announcements. This example does not require Visual Studio; everything can be done using only a web browser.

To display a list of announcements by using JavaScript

  1. Start by adding a CEWP to the right column of your home page. You can find the CEWP in the Web Part gallery under theMedia and Content category.
  2. Put the Web Part into edit mode by selecting Edit Web Part from the Web Part’s context menu. Click the link in the Web Part titled Click here to add new content.
  3. Next, edit the source HTML for the Web Part. Click the Editing Tools context-sensitive Format Text tab on the ribbon. In theMarkup Ribbon group, select Edit HTML source from the HTML drop-down button. In the HTML source dialog, add the following code.
    <!--Load the Script Loader-->
    <script src= "/SiteAssets/Scripts/Start.debug.js" type= "text/javascript"></script>
    
    <!-- Load jQuery library-->
    <script type= "text/javascript">
      Sys.loadScripts(["/SiteAssets/Scripts/jquery-1.4.2.js"], function() {
      GetAnnouncements();
      });
    </script>
    <script type= "text/javascript">
      function GetAnnouncements() {
        var soapEnv = "<soap:Envelope
    xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/’> \
          <soap:Body> \
          <GetListItems xmlns=’http://schemas.microsoft.com/sharepoint/soap/’> \
            <listName>Announcements</listName> \
              <viewFields> \
                <ViewFields> \
                  <FieldRef Name=’Title’ /> \
                  <FieldRef Name=’Body’ /> \
                  <FieldRef Name=’Expires’ /> \
                </ViewFields> \
              </viewFields> \
            </GetListItems> \
          </soap:Body> \
        </soap:Envelope>";
      jQuery.ajax({
        url: "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: GetListItemsComplete,
        contentType: "text/xml; charset=\"utf-8\""
      });
    }
    function GetListItemsComplete(xData, status) {
      jQuery(xData.responseXML).find("z\\:row").each(function () {
        $("<li>" + $(this).attr("ows_Title") + "</li>").appendTo("#Announcements");
      });
    }
    </script>
    <ul id="Announcements"></ul>
    
The GetAnnouncements function builds the SOAP message and then uses the jQuery.ajax API to call the lists.asmx web service. The jQuery.ajax calls the GetListItemsCompleted callback method when the web service returns. The GetListItemsCompletemethod parses the XML data that returns from the lists.asmx web service. As it parses each record in the XML data, it appends a list item to the Announcements list using the appendTo function.
There are two key pieces to calling various SharePoint web services. The first is to understand the exact SOAP XML that is required to call the service, and the second is to understand the returned XML data and how to parse it to extract the exact values required. Although these change between the various services, the code pattern is the same for all services. Unfortunately, discovering how to format the SOAP message can be a challenge. Although MSDN documents the methods, it does not tell you the exact SOAP format or which parameters are optional. One of the easiest ways to discover the syntax is to create a console application in Visual Studio that calls the web service you are interested in calling from JavaScript. Then use the web debugging tool Fiddler to intercept and inspect the web service calls.

No comments:

Post a Comment