Accessing SharePoint Lists with JavaScript using DP Tools Part One: The Basics

SharePoint LogoSharePoint lists are amazingly versatile for storing data in an “almost database” kind of way. For those with access to enterprise features and SharePoint Designer, accessing that data to create custom displays and reports is point-and-click easy. Those if us without such access have to get a little more… creative.

Thankfully, SharePoint provides a full roster of Web Services, accessible from client-side code, to leverage its features and data. Accessing these from JavaScript can be confounding or, at the very least, cumbersome. To address this in my work, I’ve created a set of abstractions to make the process as painless as possible. There are obviously other ways – many other ways – to achieve the same thing, this is simply my way of doing it.

  • This technique allows us to pull information from any site accessible to the client, local or not.
  • You and all intended end users must have Read Access to the site and list you’re working with. This is client-side code, after all.
  • You can pull data into other SharePoint pages, of course, but also into non-sharepoint web sites.
  • See my article , “Accessing SharePoint List with Visual Basic for Applications“, for examples of using the services with client-side applications such as Word and Excel.

These examples were developed against SharePoint 2010, but should also work in the 2007 and 2013 versions.

Assumptions and Prerequisites

This article assumes that you’re comfortable with SharePoint and JavaScript. I’ve provided a brief introduction to the topic in my article, “SharePoint Scripting Basics: Master Pages, Caching and Loading Scripts“. It assumes that you’ll be:

  • Loading script using the always handy Content Editor Web Part (CEWP).
  • Creating a separate file for code and loading it using the “Content Link” feature of the Content Editor (pasting code into a CEWP directly does work, but the reformatting that occurs is a crime against man and nature).
  • Creating a folder called “Scripts” in the “Site Assets” library (although you can use any library you prefer) and storing your files there.

The article also assumes that some support libraries, downloadable here at DepressedPress.com, are available:

  • DP_AJAX: Makes working with HTTP requests and XML much simpler. You can bundle multiple requests into a single response, manage XML documents and control error handling.
  • DP_SharePoint: Abstracts many of the pain points of SharePoint and integrates with DP_AJAX to make easy work of accessing the available Web Services.

We’ll be assuming that these scripts are available in the /SiteAssets/Scripts/ folder as well.

Gathering Your Parameters

You can use this technique with any of the available web services, but we’ll be leveraging the Lists service specifically. You’ll need the following:

  • The unique identifiers for the list and (optionally) any views that you’ll access.
  • The URL of the service itself. For the Lists service, this is normally: “http://targetsite/_vti_bin/Lists.asmx”
  • The name of the method to perform. This will depend on the service being used and the action being performed. We want to fetch data from a list, so will be using the “GetListItems” method.
  • Finally, you’ll need the parameters and values required for the method you’re calling. The GetListItems methods has several parameters, but we’ll only be leveraging the most basic ones for now.

For purposes of testing, you can use any list you have available. It will not be altered in any way.

The Code in Steps

Our example is minimalist. We’re going to access a list and present “ID” and “Title” columns. Later installments will expand upon this.

This code would be written to a separate text file and saved to a location (we’re assuming “/SiteAssets/Scripts/”). It would be loaded into a page via the “Content Link” feature of a Content Editor Web Part.

Begin by setting up the page itself. The example is very simple: a custom style and a (currently empty) DIV that will (eventually) hold our output.

    <!-- Styles -->
<style type="text/css">
    td.ColHdr {
        border-bottom: #8ebbf5 1px solid;
        font-weight: bold;
        color: #4c4c4c;
    	background-color: #ccebff;
        text-align: center;
    }
</style>

    <!-- Create a DIV to display the data -->
<div id="Display_Data"></div>

We load our support scripts. Replace the path used with the correct one for your site. Alternatively, these could be loaded in the Master Page (in the head of the document) if you’d like them to be loaded and available on every page automatically.

    <!-- Scripts -->
<script type="text/javascript" src="/SiteAssets/Scripts/DP_Ajax.js"></script>
<script type="text/javascript" src="/SiteAssets/Scripts/DP_SharePoint.js"></script>

We start the main script and set up the environment.

  • An instance of a DP_AJAX RequestPool, MyPool, is created. This runs in the background and manages HTTP calls.
  • A new DP_AJAX Request object, MyRequest, is created. The first parameter, ProcessRequest, names the function that will process the returned data.
  • Parameters for the web service call are collected as a literal JavaScript object. In this case, we’ll only need the name of the list.
  • We use DP_SharePoint.callService() to set up the web service call. We pass it the Request object, the URL of the service to call, the method to use and the parameters collected on the previous line.
  • Finally, we add the prepared request to the pool. The request will be picked up, sent to the server and the response then sent to the ProcessRequest() function.
<script type="text/javascript" charset="utf-8">

    // Create a new RequestPool
MyPool = DP_AJAX.createPool(2);
    // Create the Request
MyRequest = DP_AJAX.createRequest(ProcessRequest, null, null, null, true, true);
    // Create the parameter sets for the calls
MyParams = {"listName":"ListName"};
    // Add the calls to the service
DP_SharePoint.callService( MyRequest, ServiceURL, "GetListItems", MyParams );
    // Add the request to the pool
MyPool.addRequest(MyRequest);

The largest part of the code – the display of the data – is also the least interesting, overall. The example provides a framework for working with the response, but will obviously need to be modified and expanded to your specific needs.

The function takes the response, an XML object, as a parameter. We then:

  • Create a variable, HTML, to hold the output. We then add a header row for the table to this.
  • We determine if there was an error in the response. If there’s an error, the text “There was a problem.” is output. (The DP_AJAX.getElementsWithNS() method is used to access the namespaces within the XML in a cross-browser manner.)
  • We use the DP_SharePoint.getRows() method to return just the data rows – still as XML – from the response.
  • We check, using DataRows.length, if no rows were returned. If so, the text “No items found.” is output.
  • Assuming no errors were encountered and there is data to display, we loop over the available rows to create table rows and add them to the output HTML.
  • We close the HTML table.
  • Finally, we insert the output HTML into the DIV, Display_Data, created earlier and end the function and the script.
    // Process and display the results
function ProcessRequest( Response ) {

    var HTML;
        // Create header and start table
    HTML = HTML + '<table style="table-layout: fixed;">\
        <tr>    <td class="ColHdr">ID</td>\
                <td class="ColHdr">Title</td>\
        </tr>';
        // Determime if there was an error
    if ( DP_AJAX.getElementsWithNS(Response, "Fault", "soap").length == 0 ) {
            // Get Data Rows
        var DataRows = DP_SharePoint.getRows(Response);
            // Loop Over Rows to Collect information
        if ( DataRows.length > 0 ) {
            for ( var Cnt = 0; Cnt < DataRows.length; Cnt++ ) {
                    // Create Row
                HTML = HTML + '<tr>\
                    <td>' + DataRows[Cnt].getAttribute("ows_ID") + '</td>\
                    <td>' + DataRows[Cnt].getAttribute("ows_Title") + '</td>\
                    </tr>';
            };
        } else {
            HTML = HTML + '<tr><td colspan="2">No items found.</td></tr>';
        };

    } else {
        HTML = HTML + '<tr><td colspan="2">There was a problem.</td></tr>';
    };
    HTML = HTML + '</table>';

        // Present the Results
    document.getElementById("Display_Data").innerHTML = HTML;

};

</script>

The debugging capabilities of modern browsers (usually accessible via the F12 key) are invaluable for diagnosing problems with internal HTTP calls. Common problems include malformed requests and permission issues.

In Conclusion

Accessing SharePoint data directly via script provides incredible versatility. I’ve used the technique to:

  • I’ve pulled only the contact information for only the current on-call associate from a list containing the entire month of data and displayed it on our public team site.
  • I’ve filtered and displayed vacation and holiday information from other enterprise sites on our private team site.
  • I’ve created many custom reports for various business needs.

The example above is, as noted, the most basic example possible. It can be expanded on in many ways. Future articles will cover:

  • Using Views and CAML queries to filter and sort the data from your lists.
  • Using the many CleanSP_ methods of DP_SharePoint to easily clean and format data returned by the web services.
  • Using the advanced capabilities of DP_SharePoint and DP_AJAX to manage calls from multiple lists and combine data from those calls.
  • Using XSL transformations to easily create custom reports and HTML output.

It’s also worth noting that retrieving data from a list is only scratching the surface of what’s possible using the same technique with other web services and methods. You can update a list with user data, pull site metdata and access groups and permissions information. DP_SharePoint.callService() can be used to streamline access to any of the many services available.

Leave a Reply