Search code examples
javascriptsharepoint-2010sharepoint-designersharepoint-list

Read Sharepoint List Value using javascript and set to variable


I feel I have a fairly simple problem but every solution online is seriously complicated. I am in SharePoint designer 2010 and I am not a programmer but I can get by. I have a SP list with Contract Numbers and when you click the contract number it brings you to the item. I just want JavaScript code that will read the value from the list (by ID or however) and store it in a variable.

For example:

var siteUrl = 'https://...';
var itemID = 22;
var TargetListItem;
Function onLoad(){
var context = new SP.ClientContent(siteUrl);
var web = context.get_web().get_lists().getByTitle('Data Call');
var list = web.getItemById(itemID);
context.load(list, 'Contract Number');

var value = list.get_item('Contract Number');

var url = "/sites/... " + value + "...";
return url
}

The code works if I hard-code value so that the URL returned has a parameter, but not when I set value above. Please if anyone has a really simple way to accomplish this let me know!


Solution

  • You are missing SP.ClientContext.executeQueryAsync method that executes the current pending request asynchronously on the server

    SP.ClientContext.executeQueryAsync method has the following signature:

    SP.ClientContext.executeQueryAsync(succeededCallback, failedCallback)
    

    and since it is async method you cant return from your method, but have to declare succeededCallback function that contains the returned results.

    When working with asynchronous API such as JSOM the following patterns are commonly used:

    • Using nested callbacks
    • Using the promises pattern

    Please refer Asynchronous programming in apps for Office article to get acquainted with asynchronous programming for SharePoint.

    The below example demonstrates how to get list item using callback approach:

    function getItem(listTitle,itemId,success,error){  
       var context = SP.ClientContext.get_current();
       var web = context.get_web();
       var list = web.get_lists().getByTitle(listTitle);
       var listItem = list.getItemById(itemId);
       context.load(listItem);
    
       context.executeQueryAsync(
       function() {
            success(listItem);
       },
       error
      );
    }
    

    Example

    getItem('Data Call', 22,
      function(item){
           var result = item.get_item('Contract Number'); 
      },
      function(sender,args){
           console.log(args.get_message());
      }
    );
    

    References

    How to: Create, Update, and Delete List Items Using JavaScript

    Asynchronous programming in apps for Office