Sharepoint - SP2013: Get item by id from javascript function?

Use this function from msdn

  //Get the list item from the Announcements list whose Id is 4. Note that this is the ID of the item in the list, not a reference to its position in the collection.
   var itemId = 4;   
   var targetListItem;

   function runCode() {
     var clientContext = new SP.ClientContext(); 
     var targetList = clientContext.get_web().get_lists().getByTitle('Announcements');
     targetListItem = targetList.getItemById(itemId);
     clientContext.load(targetListItem, 'Title');
     clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
   }

   function onQuerySucceeded() {

       alert('Request succeeded. \n\nRetrieved Item is: ' + targetListItem.get_item('Title'));

   }

   function onQueryFailed(sender, args) {
     alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
   }

Change list name 'Announcements' and item id '4' to yours.


You need to use JSOM or REST to get the item. This in return means you must implement some kind of asynchronous behavior in GetDetailInfo.

For example (usin jQuery ajax):

function GetDetailInfo(itemID, callback) {
  $.ajax({
    url: "/_api/Web/Lists/getByTitle('EmployeeDetailInfo')/Items/getById(" + itemID + ")", 
    headers: {
      Accept: "application/json; odata=verbose"
     }
   }).success(callback);
}

Then you call it like this:

GetDetailInfo(1, function(item) {
   // work with item
});

This approach should work fine in display templates, and we have done this before without issues. Although note that this approach will create 1 REST call for each line, you could think of some way to get around that problem.

Tags: