Print This Post

Examples for the SharePoint and Office Live javascript API

The following examples illustrate the use of the javascript API for SharePoint and Office Live. These examples are intended to demonstrate the core uses of the API for solution developers.


1- Get the full definition of a list

The lists web service contains a method GetList which can be used to obtain the XML definition of a list.
This definition contains a great deal of information about the list. The result is a fragment of CAML as described on MSDN.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var listDef = lists.getList('Pages');

      if (listDef.status == 200)
      {
          // The list definition is in listDef.resultNode and is a browser specific XML document
      }
      else
      {
          alert('There was an error: ' + listDef.statusText);
      }

References

Related sample XML packets



2- Get the full definition of a list and associated view

The lists web service contains a method GetListAndView which can be used to obtain the XML definition of a list and an associated view. This definition contains a great deal of information about the list. The result is a fragment of CAML as described on MSDN.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var listDef = lists.getListAndView('Tasks', '{4011C1CE-A840-4BEB-89E3-A42DF3E3711E}');

      if (listDef.status == 200)
      {
        // The list definition is in listDef.resultNode and is a browser specific XML document
      }
      else
      {
        alert('There was an error: ' + listDef.statusText);
      }

References

Related sample XML packets



3- Get the basic detail of all lists in a site

The lists web service contains a method GetListCollection which can be used to obtain the basic XML details of all lists in a site. Once these have been retrieved they can be enumarated and further details loaded as required. The result is a fragment of CAML as described on MSDN.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var listCollection = lists.getListCollection();

      if (listCollection.status == 200)
      {
        var items = listCollection.responseXML.getElementsByTagName('List');

        alert('There are ' + items.length + ' lists in the site.');

        for (var i=0; i<items.length; i++)
        {
          // Do something
          alert(items[i].getAttribute('Title') + ' ' + items[i].getAttribute('ID'));
        }
      }
      else
      {
        alert('There was an error: ' + listCollection.statusText);
      }

References

Related sample XML packets



4- Get the GUID of a list from it’s name

Some web services require that the internal guid of a list be passed as a paramter. Since this guid can potentially change between site backups and certainly when the solution is shipped this can be a problem for solution developers. The GetListGuid function takes a list name and returns the guid of the list.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      function getListGuid(baseUrl, listName)
      {
          var res;
          var lists = new SPAPI_Lists('');
          res = lists.getList(listName);

          if (res.status == 200)
          {
              var listID = -1;

              if (res.resultNode != null)
              {
                  listID = res.resultNode.childNodes[0].getAttribute('ID');
              }

              return { listID : listID, fullResult : res };
          }
          else
          {
              return { listID : null, fullResult : res };
          }
      }

References

Related sample XML packets



5- Querying a list using the Lists web service

The GetListItems method of the lists web service can be used to query a list using CAML query notation and return list items that match the criteria. Of the different ways to return list data this is probably the easiest and most recommended way of doing so.

By default, GetListItems returns the records in a list view- either the default view or a custom view definition. In this way the filtering and ordering may be specified by the view definition. However, the method also allows the query, row limit, and list of fields to be changed allowing custom queries to be executed.

See the links given in the references section for more information on the parameters of this method.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      // Return all items in the default view of MyList

      var lists = new SPAPI_Lists('http://localhost')
      var items = lists.getListItems('MyList');

      if (items.status == 200)
      {
        var rows = items.responseXML.getElementsByTagName('z:row');

        document.getElementById('output').value = items.responseText;
        for (var i=0; i<rows.length; i++)
        {
          // Do something with the row
        }
      }
      else
      {
        alert('There was an error: ' + items.statusText);
      }     

      // Return the first 5 items where ID < 10. Only return the Title and ID columns and do not include mandatory columns.
      var lists = new SPAPI_Lists('http://localhost')
      var items = lists.getListItems(
      'MyList',   // listName
      '',         // viewName
      '<Query><Where><Lt><FieldRef Name="ID"/><Value Type="Counter">10</Value></Lt></Where></Query>',  // query
      '<ViewFields><FieldRef Name="ID"/><FieldRef Name="Title"/></ViewFields>',  // viewFields
      5,  // rowLimit
      '<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns></QueryOptions>'  // queryOptions
      );

      if (items.status == 200)
      {
        var rows = items.responseXML.getElementsByTagName('z:row');

        document.getElementById('output').value = items.responseText;
        for (var i=0; i<rows.length; i++)
        {
          // Do something with the row
        }
      }
      else
      {
        alert('There was an error: ' + items.statusText);
      }

References

Related sample XML packets



6- Querying a list using the List Data Retrieval Service

The List Data Retrieval Service allows lists to be queried using CAML notation. This service is one of several ways to search SharePoint and Office Live lists. The service allows for complex search criteria, sorting, result count limiting, and selection of fields. The javascript API provides a specific helper method to assist in calling this service.

The results are in the form of a CAML fragment containing an element for every row in the result set.

The example selects all pages from the site with an ID greater than or equal to 5. These are sorted in descending order of ID and limited to 10 results. The getElementsById method is then used to extract the rows and display their attributes one by one.

Services JS API Includes Required
  • dspsts.asmx
  • SPAPI_Core.js
  • SPAPI_dspsts.js

Code sample


      var dspsts = new SPAPI_dspsts('http://localhost');
      var res = dspsts.queryRequest(
      "{CFD2A33E-EE89-47F3-9E28-24442E598326}", // listGuid
      "<Field Name='ID'/><Field Name='Title'/>", // fields
      "<Geq><FieldRef Name='ID' /><Value Type='Counter'>5</Value></Geq>", // where
      "<OrderField Name='ID' Type='xsd:int' Direction='DESC'/>", // orderBy
      10  // rowLimit
      );

      if (res.status == 200)
      {
          var rows = res.responseXML.getElementsByTagName('Row');

          alert('There were ' + rows.length + ' results.');

          for (var i=0; i<rows.length; i++)
          {
              var item = rows[i];
              // Do something with the row
              alert('The page with ID ' + item.getAttribute('ID') + ' has a title of ' + item.getAttribute('Title'));
          }
      }
      else
      {
          alert('There was an error: ' + res.statusText);
      }     

References



7- Create a new list from an existing list template

The AddList method of the lists web service may be used to create a new list based on an existing list template.

The example shown creates a new tasks list called NewTasks.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.addList('NewTasks', 'My new task list', lists.LIST_ID_TASKS)

      if (res.status == 200)
      {
        alert('The new list was created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

Remarks

The list template IDs you will need to use this method are defined as constants in the SPAPI_Lists class.

      /* List template IDs */
      this.LIST_ID_ADMIN_TASKS        = 1200    // Administrator tasks list
      this.LIST_ID_ANNOUNCEMENTS      = 104     // Announcements list
      this.LIST_ID_BLOG_CATEGORIES    = 303     // Blog Categories list
      this.LIST_ID_BLOG_COMMENTS      = 302     // Blog Comments list
      this.LIST_ID_BLOG_POSTS         = 301     // Blog Posts list
      this.LIST_ID_CONTACTS           = 105     // Contacts list
      this.LIST_ID_CUSTOM_GRID        = 120     // Custom grid for a list
      this.LIST_ID_CUSTOM_WORKFLOW    = 118     // Custom Workflow Process
      this.LIST_ID_DATA_CONNECTIONS   = 130     // Data Connection library
      this.LIST_ID_SATA_SOURCES       = 110     // Data sources
      this.LIST_ID_DISCUSSION_BORAD   = 108     // Discussion board
      this.LIST_ID_DOCUMENT_LIBRARY   = 101     // Document library
      this.LIST_ID_EVENTS             = 106     // Events list
      this.LIST_ID_GANTT_TASKS        = 150     // Gantt Tasks list
      this.LIST_ID_GENERIC            = 100     // Generic list
      this.LIST_ID_ISSUE_TRACKING     = 1100    // Issue tracking
      this.LIST_ID_LINKS              = 103     // Links list
      this.LIST_ID_LIST_TEMPLATE      = 114     // List template gallery
      this.LIST_ID_MASTER_PAGE        = 116     // Master pages gallery
      this.LIST_ID_MEETING_AGENDA     = 201     // Meeting Agenda list
      this.LIST_ID_MEETING_ATTENDEES  = 202     // Meeting Attendees list
      this.LIST_ID_MEETING_DECISIONS  = 204     // Meeting Decisions list
      this.LIST_ID_MEETING_OBJECTIVES = 207     // Meeting Objectives list
      this.LIST_ID_MEETING_SERIES     = 200     // Meeting Series list
      this.LIST_ID_MEETING_TEXT_BOX   = 210     // Meeting text box
      this.LIST_ID_MEETING_TTB        = 211     // Meeting Things To Bring list
      this.LIST_ID_MEETING_WS_PAGES   = 212     // Meeting Workspace Pages list
      this.LIST_ID_NO_CODE_WORKLOFWS  = 117     // No-Code Workflows
      this.LIST_ID_PERSONAL_DOCLIB    = 2002    // Personal document library
      this.LIST_ID_PICTURE_LIBRARY    = 109     // Picture library
      this.LIST_ID_PORTAL_SITE_LIST   = 300     // Portal Sites list
      this.LIST_ID_PRIVATE_DOCLIB     = 2003    // Private document library
      this.LIST_ID_SITE_TEMPLATES     = 111     // Site template gallery
      this.LIST_ID_SURVEY             = 102     // Survey
      this.LIST_ID_TASKS              = 107     // Tasks list
      this.LIST_ID_USER_INFO          = 112     // User Information list
      this.LIST_ID_WEB_PARTS          = 113     // Web Part gallery
      this.LIST_ID_WIKI_PAGES         = 119     // Wiki Page library
      this.LIST_ID_WORKFLOW_HISTORY   = 140     // Workflow History
      this.LIST_ID_XML_FORMS          = 115     // XML Form library
      /*-------------------*/
      

References



8- Delete a list

The DeleteList method of the lists web service may be used to delete a list and all list items. The list is moved to the recycle bin prior to being completely removed from the system.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.deleteList('MyList');

      if (res.status == 200)
      {
        alert('The list was deleted.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

References



9- Create one or more new list items

Creation of new list items is carried out using the UpdateListItems method of the lists web service. This method takes a batch element as a parameter. The batch element contains a number of fields with appropriate values to populate the list item. The javascript API provides a utility method called quickAddListItem which makes this process a little easier by taking care of the XML batch production automatically.

To use quickAddListItem pass in a list name and a javascript object which contains properties and value corresponding to the list item. You can use the javascript shorthand notation for object creation to make this easy.

For example a basic list item may be expressed as:


{ Title: 'List item title', Description: 'List item description' }

You may also choose to create a number of list items at the same time by passing in an array of objects, each one of which will represent a list item. All of the items will then be created in the same list. If creation of any item fails then processing will continue on to the next item. You can use javascript shorthand array notation to make this easy.


[ { Title: 'My new item 3' }, { Title: 'My new item 4' } ]

If you need to create items within a folder simply specify the optional rootFolder parameter. Let’s say you’re creating items in a list called MyList. There’s a folder in there called Folder1. In Folder1 there’s another folder called Folder2. If you want to create items inside Folder2 you set rootFolder to /Lists/MyList/Folder1/Folder2.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.quickAddListItem('MyList', { Title: 'My new item 2', Description: 'My Description' });

      if (res.status == 200)
      {
        alert('The new list item was created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

      // Or to create multiple items....

      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.quickAddListItem('MyList', [ { Title: 'My new item 3' }, { Title: 'My new item 4' } ]);

      if (res.status == 200)
      {
        alert('The new list items were created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

      // Or to create items in a folder
      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.quickAddListItem('MyList', [ { Title: 'My new item 3' }, { Title: 'My new item 4' } ], '/Lists/MyList/Folder1/Folder2');

      if (res.status == 200)
      {
        alert('The new list items were created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

References



10- Update one or more list items

Updating of list items is carried out using the UpdateListItems method of the lists web service. This method takes a batch element as a parameter. The batch element contains a number of fields with appropriate values to update the list item. The javascript API provides a utility method called quickUpdateListItem which makes this process a little easier by taking care of the XML batch production automatically.

To use quickUpdateListItem pass in a list name and a javascript object which contains properties and value corresponding to the list item. You can use the javascript shorthand notation for object creation to make this easy. For example a basic list item may be expressed as:


{ ID: 8, Title: 'List item title', Description: 'List item description' }

Note that for an update to occur, the ID value must be populated with the id of the target list item. All columns other that the ID will be updated. Columns which are not expressed will be left as they are in the list.

You may also choose to update a number of list items at the same time by passing in an array of objects, each one of which will represent a list item and contain the appropriate ID. All of the items will then be updated at the same time. If updating of any item fails then processing will continue on to the next item. You can use javascript shorthand array notation to make this easy.


[ { ID: 8, Title: 'My new item 3' }, { ID: 9, Title: 'My new item 4' } ]

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')

      // Update the title of the item with ID 8
      var res = lists.quickUpdateListItem('MyList', { ID: 8, Title: 'Updated title 1' } );

      if (res.status == 200)
      {
        alert('The list item was updated.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

      // Or to update multiple items....

      var lists = new SPAPI_Lists('http://localhost')

      // Update the titles of the items with ID 8 and 9
      var res = lists.quickUpdateListItem('MyList', [ { ID: 8, Title: 'Updated title 1' }, { ID: 9, Title: 'Updated title 2' } ]);

      if (res.status == 200)

      {
        alert('The list items were updated.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

References



11- Delete one or more list items

Deletion of list items is carried out using the UpdateListItems method of the lists web service. This method takes a batch element as a parameter. The batch element contains a field element containing an ID of a list item to delete. The javascript API provides a utility method called quickDeleteListItem which makes this process a little easier by taking care of the XML batch production automatically.

To use quickDeleteListItem pass in a list name and either a single ID number or array of ID numbers to delete.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.quickDeleteListItem('MyList', 4);

      if (res.status == 200)
      {
        alert('The list item was deleted.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

      // Or to delete multiple items....

      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.quickDeleteListItem('MyList', [ 1, 2, 3, 4]);

      if (res.status == 200)
      {
        alert('The list items were deleted.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

References



12- Create a new folder within a list

Creation of list folders is carried out using the UpdateListItems method of the lists web service. This method takes a batch element as a parameter. The batch element contains a field element containing the name of the folder and FSObjType of 1 (folder). The javascript API provides a utility method called createFolder which makes this process a little easier by taking care of the XML batch production automatically.

To use createFolder pass in a list name and a new folder name.

If you need to create a folder within a folder simply specify the optional rootFolder parameter. Let’s say you’re creating items in a list called MyList. There’s a folder in there called Folder1. In Folder1 there’s another folder called Folder2. If you want to create a new folder inside Folder2 you set rootFolder to /Lists/MyList/Folder1/Folder2.

Services JS API Includes Required
  • Lists.asmx
  • SPAPI_Core.js
  • SPAPI_Lists.js

Code sample


      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.createFolder('MyList', 'TestFolder2');

      if (res.status == 200)
      {
        alert('The folder was created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

      // Or to create a folder within a folder

      var lists = new SPAPI_Lists('http://localhost')
      var res = lists.createFolder('MyList', 'TestFolder2', '/Lists/MyList/TestFolder');

      if (res.status == 200)
      {
        alert('The folder was created.');
      }
      else
      {
        alert('There was an error: ' + res.statusText);
      }

References



13- Performing a keyword search

The Query Service allows developers to run keyword and SQL queries against a site collection. To do this, a CAML QueryPacket is submitted to the Query method of the service. This query packet contains the definition of the query. Creation of these packets is simpified in the javascript API through the SPAPI_QueryPacket in the SPAPI_Types.js library.

Services JS API Includes Required
  • Search.asmx
  • SPAPI_Core.js
  • SPAPI_Search.js
  • SPAPI_Types.js

Code sample


      var lists = new SPAPI_Search('');

      // Create the new query
      // Type = SQL_Query_Type_Keyword
      // Query = Sharepoint
      // Fields to return = Title,Path,Description,Write,Rank,Size
      var query = new SPAPI_QueryPacket(SPAPI_Query_Type_Keyword, 'Sharepoint', 'Title,Path,Description,Write,Rank,Size');

      // Add a new sort property - sort by ID, descending, first sort property
      query.addSortProperty('ID', false, 0);

      // Add a new sort property - sort by Title, ascending, second sort property
      query.addSortProperty('ID', true, 1);

      var res = lists.query(query.getXML());

      if (res.status == 200)
      {
         // Get the response document
         var resultDocument = query.getResultDocument(res.responseXML);
         var status = resultDocument.getElementsByTagName('Response')[0].getElementsByTagName('Status')[0].childNodes[0].nodeValue;

         alert('The status of the search was: ' + status);

         if (status == 'SUCCESS')
         {
              var count = resultDocument.getElementsByTagName('Range')[0].getElementsByTagName('Count')[0].childNodes[0].nodeValue;
              alert(count + ' results were returned');

              var items = resultDocument.getElementsByTagName('Response')[0].getElementsByTagName('Document');

              for (var i=0; i<items.length; i++)
              {
                  // Process each document result
              }
         }
      }
      else
      {
          alert('There was an error processing the search');
      }

References

Related sample XML packets


14- Performing a full text search

The Query Service allows developers to run keyword and SQL queries against a site collection. To do this, a CAML QueryPacket is submitted to the Query method of the service. This query packet contains the definition of the query. Creation of these packets is simpified in the javascript API through the SPAPI_QueryPacket in the SPAPI_Types.js library.

By setting the query type to SPAPI_Query_Type_SQL it is possible to execute a full text query. In this case the field list in the SPAPI_QueryPacket constructor is not required. The example below returns all people in the SharePoint Server shared services provider who’s preferred name begins with A.

Services JS API Includes Required
  • Search.asmx
  • SPAPI_Core.js
  • SPAPI_Search.js
  • SPAPI_Types.js

Code sample


      var lists = new SPAPI_Search('');

      // Create the new query
      // Type = SPAPI_Query_Type_SQL
      // Query = Sharepoint
      // Fields to return = Title,Path,Description,Write,Rank,Size
      var query = new SPAPI_QueryPacket(SPAPI_Query_Type_SQL,
                  "SELECT PreferredName, Department, Manager, AboutMe,"+
                  "Title, Path, Description, Write, Rank, Size  FROM SCOPE() where \"scope\"='People' "+
                  "AND PreferredName LIKE 'A%'", '');

      // Add a new sort property - sort by PreferredName, ascending, first sort property
      query.addSortProperty('PreferredName', true, 0);

      var res = lists.query(query.getXML());

      if (res.status == 200)
      {
         // Get the response document
         var resultDocument = query.getResultDocument(res.responseXML);
         var status = resultDocument.getElementsByTagName('Response')[0].getElementsByTagName('Status')[0].childNodes[0].nodeValue;

         alert('The status of the search was: ' + status);

         if (status == 'SUCCESS')
         {
              var count = resultDocument.getElementsByTagName('Range')[0].getElementsByTagName('Count')[0].childNodes[0].nodeValue;
              alert(count + ' results were returned');

              var items = resultDocument.getElementsByTagName('Response')[0].getElementsByTagName('Document');

              for (var i=0; i<items.length; i++)
              {
                  // Process each document result
              }
         }
      }
      else
      {
          alert('There was an error processing the search');
      }

References

Related sample XML packets

There Are 17 Responses So Far. »

  1. hi Darren,
    i have created my list template, and i wanna use it for my future lists creation. how can i get its template id?

  2. Vivek,

    Download the .stp file to your local computer. The stp file is actually a cabinet file. Rename it .cab and you will be able to open it with Windows Explorer. Next find the manifest.xml file and open it up in Internet Explorer. Towards the top of the file you will find the template ID encoded in the XML.

    Cheers,
    Darren

  3. Hi Darren,

    This seems like the perfect solution for my needs. However I just don’t quite understand the mechanics of deploying the solution.

    1. Where on my server do I put your javascript files ?
    2. How do I reference (include) them in javascript written in Sharepoint content part ?
    3. How about a step by step sample , where the end result would be a sharepoint page containing a block displaying user’s name ?

    cheers,
    Petri.

  4. Hi Petri,

    If you have full control of your server:

    1) Locate the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS folder.
    2) In there create a new folder called JSAPI.
    3) Place the extracted .js files in there.
    4) Enter the following script in a content editor web part.


    <script type="text/javascript" src="/_layouts/JSAPI/SPAPI_Core.js"></script>
    <script type="text/javascript" src="/_layouts/JSAPI/SPAPI_Lists.js"></script>

    <div id="username_div">
    </div>

    <script type="text/javascript">

    function getCurrentUserName()
    {
    var lists = new SPAPI_Lists('');
    var items = lists.getListItems(
    'User Information List',
    '',
    '<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Counter">' + _spUserId + '</Value></Eq></Where></Query>', // query
    '<ViewFields><FieldRef Name="Name"/></ViewFields>',
    1, // rowLimit
    '' // queryOptions
    );

    if (items.status == 200)
    {
    var rows = items.responseXML.getElementsByTagName('z:row');

    if (rows.length == 1)
    {
    return rows[0].getAttribute(’ows_Name’);
    }
    else
    {
    return null;
    }
    }
    else
    {
    return null;
    }
    }

    function showUserName()
    {
    // Test code
    var userName = getCurrentUserName();

    if (userName != null)
    {
    document.getElementById('username_div').innerText = 'Welcome: ' + userName;
    }
    else
    {
    document.getElementById('username_div').innerText = 'User name not found';
    }
    }

    _spBodyOnLoadFunctionNames.push('showUserName');
    </script>

    If you don’t have full access:

    1) Open SharePoint Designer and connect to your site.
    2) Create a new folder called JSAPI at the root of the site.
    3) Copy the extracted .js files to the folder by dragging them from Windows Explorer to SP Designer.
    4) Paste the same script as above into a content editor web part except replace the script includes at the top with the following lines:


    <script type="text/javascript" src="/JSAPI/SPAPI_Core.js"></script>
    <script type="text/javascript" src="/JSAPI/SPAPI_Lists.js"></script>

    You can also choose to put the script includes into your master page in the head section if you wish. If you are going to use the libraries extensively then this would be best.

    Cheers,
    Darren

  5. Hi Darren,

    I am using your scripts with great ease and success except for one area.

    I cannot get the SortByProperties to work with the search web service. When I look at your file named JSAPI_Types on line 101 and 106 I can see that you construct the sort by properties using SortProperties and within that element a Property element but the Microsoft SDK says these elements should be SortByProperties and SortByProperty elements.

    Either way the SortByProperty I pass in, which I have confirmed is a managed property has no affect on the search results sort order.

    I have added an “order by MANAGED PROPERTY” string to the QueryText variable to get results successfully sorted by a managed property but it would be good to understand why the SortByProperties are not working.

    Do you know what the correct syntax is for these elements and can you confirm a working version of this?

    Also would it be possible to make a change to the SPAPI_QueryPacket function to expose the Count property so that it be configurable when when creating the SPAPI_QueryPacket object. I would like to be able to specify a large number or 0 for different calls to this search web service.

    Thank you for the incredible work you have done to simplify this process of calling the SharePoint web services from JavaScript.

  6. Hi Darren,

    I used your Lists API successfully, I have a minor problem and this is when I try to pull up information from a Library sometimes I can’t get the Title, for some reason it comes to null, do you know why this is? This is part of my code:

    //Set the query to get the items accordingly

    var items = lists.getListItems(listName,”,’1′,”,”,’TRUE’);

    // and here to get the item details..

    var itemTitle = item.getAttribute(’ows_Title’);
    var itemUrl = item.getAttribute(’ows_FileRef’);
    var itemID = item.getAttribute(’ows_ID’);

    For some reason I am able to get the last two but not the Title, do you know why that might be?

    Also, thanks for making this awesome API, you’re the best!

  7. Hi Saul,

    Take a look at items.responseText. This will give you the full XML that is returned. Look at your items in there and see if the title attribute is present. You can also specify the title column explicitly in the ViewFields parameter to make sure it is returned.
    eg:

    var items = lists.getListItems(listName,'','<Query/>','<ViewFields><FieldRef Name="ID"/><FieldRef Name="Title"/><FieldRef Name="FileRef"/></ViewFields>', 1, '');

    Cheers,
    Darren

  8. Hello,

    Where can we find the SPAPI_Core.js and SPAPI_Lists.js files?

    Thanks,
    Paulo

  9. Paulo- in the downloads section:

    http://darrenjohnstone.net/download/12/.

    Cheers,
    Darren

  10. Hi Darren, this is really useful stuff, and I would like to try and use it to customize my OfficeLive account but I couldn’t find any examples that show how we can authenticate our request to OL.
    Is there an example that shows how to do this?

  11. [...] Here is some examples http://darrenjohnstone.net/2008/07/22/examples-for-the-sharepoint-and-office-live-javascript-api/ [...]

  12. [...] When I first installed SharePoint, I was amazed with the many ways I could access data (your mileage may vary depending on licensing options): user interface, web services, SharePoint Services API, RSS, email alerts, workflows, Business Data Catalog, Excel Services, Stssync protocol (Outlook Integration), Stsadm command line, T-SQL (unsupported), and RPC/URL protocols (owssvr.dll). Well, add to that list (and your Power User Toolbox) the SharePoint and Office Live JavaScript API. [...]

  13. Great framework!

    Have you considered jquery for the XML result parsing?

    See http://marcgrabanski.com/article/jquery-makes-parsing-xml-easy for instance. Seems like it would simplify the code for examples 3-6 and 13-14 above.

  14. Darren,

    Great work here!

    How would the GetListItems method be used to return a filtered lookup list in a SharePoint form? I’m trying to combine it with something like the following, from http://blog.u2u.info/DottextWeb/patrick/articles/466.aspx.

    var lookup = document.getElementsByName(”urn:schemas-microsoft-com:office:office#Contact”);
    lookup(0).innerHTML = “”;
    var data = document.forms(0).LookupFilter;
    for (i=0;i<data.options.length;i++)
    {
    var optionText = data.options(i).innerText;
    var optionValue = data.options(i).value;
    var opt = document.createElement(”OPTION”);
    lookup(0).options.add(opt);
    opt.innerText = optionText;
    opt.value = optionValue;
    }

    Thanks,
    Felder

  15. Hi Darren,

    Great piece of work.. :-)..

    I was wondering how to store the output into a session or server container that could be used later.

    Cheers

  16. Sir,

    Thank you very much for this helpful library. Installing webparts was going to be a possible yet cumbersome solution, but thanks to your library the code has remained simple.

    Thanks again.

  17. This is an extremely useful approach. Especially for the common case where site application developers are not allowed to add code to the sharepoint server. The javascript option is an elegant solution for this environment. Still busy figuring out how i can extend your approach to also deal with uploading files to a document library, where sub-website developers are forced to use the rather awkward and inflexible upload/editform combo.

Post a Response