5

I am trying to use JavaScript to get all the items in a document library. I am able to get it to work, but for the life of me I cannot get the title, name or path to the file to come back. I can get ID, modified and any other custom columns I have on the list.

I have used the code right from the sharepoint api. but here it is if you wanna see it

function getRowsFromList(LIST_URL, LIST_GUID, RETURN_FIELDS, params)
{
  var clientContext = new SP.ClientContext('/team');
  var oList = clientContext.get_web().get_lists().getByTitle('KML');

  var camlQuery = new SP.CamlQuery();
  camlQuery.set_viewXml('<View><Query><Where><Leq><FieldRef Name=\'ID\'/><Value Type=\'Number\'>100</Value></Leq></Where></Query><RowLimit>50</RowLimit></View>');
  this.collListItem = oList.getItems(camlQuery);

  clientContext.load(collListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
  var listItemInfo = '';
  var listItemEnumerator = collListItem.getEnumerator();
  var arr = [];
  while (listItemEnumerator.moveNext()) {
      var oListItem = listItemEnumerator.get_current();
      var File = oListItem.get_file();
      listItemInfo += '\n ID: ' + oListItem.get_id() + 
          '\n Name: ' + oListItem.get_item('Title');
      arr.push(oListItem.get_id());
  }
  alert(listItemInfo.toString());
  buildMenu(arr);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

I am calling my function like this...

ExecuteOrDelayUntilScriptLoaded(init, "sp.js");

I am linking my js through the master page like this...

 <SharePoint:ScriptLink language="javascript" name="sp.js" OnDemand="true" runat="server" LoadAfterUI="true" Localizable="false"/>
 <SharePoint:ScriptLink language="javascript" name="sp.runtime.js" OnDemand="true" runat="server" LoadAfterUI="true" Localizable="false"/>
 <SharePoint:ScriptLink language="javascript" name="sp.core.js" OnDemand="true" runat="server" LoadAfterUI="true" Localizable="false"/>
 <SharePoint:ScriptLink language="javascript" name="core.js" OnDemand="true" runat="server" LoadAfterUI="true" Localizable="false"/>

Please let me know if you have any questions... No error gets thrown, the value that returns is just null, when thats not the case.

3
  • Is init the name of your function where getRowsFromList is called from? Or is it just a placeholder to demonstrate the pattern you're using? I understand the intent of your camlQuery is to select specific objects, but if you just use an empty string or SP.CamlQuery.createAllItemsQuery() for the query are you still unable to retrieve the title or other fields? Also what value is returned as null? oListItem.get_item('Title')?
    – John-M
    Commented Aug 18, 2014 at 21:20
  • init does some stuff and then calls getRowsFromList
    – lovejotd
    Commented Aug 20, 2014 at 15:02
  • No matter what I do for my query, I still done get title. and yes it is the oListItem.get_item('Title') that returns null. It doesn't throw an error, like when a field isnt returned, it just says null
    – lovejotd
    Commented Aug 20, 2014 at 15:04

3 Answers 3

7

In order to retrieve File or Folder properties you could use the following associated List Item properties:

  • FileRef - returns File/Folder relative Url
  • FileLeafRef - returns File/Folder name

Example

function getListItems(listTitle,success,error)
{
  var context = SP.ClientContext.get_current(); 
  var list = context.get_web().get_lists().getByTitle(listTitle);
  var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
  context.load(items);
  context.executeQueryAsync(
     function() {
        success(items);
     },  
     error
  );
}


getListItems('Documents',
   function(items){
       var e = items.getEnumerator();
       while (e.moveNext()) {
           var item = e.get_current();
           console.log(item.get_item('FileLeafRef'));  //print File or Folder Name
           console.log(item.get_item('FileRef')); //print File or Folder Url
        }
   },
   function(sender,args){
      console.log(args.get_message());
   }
);
3
  • Thank you!!! This worked for me, combining the createAllItemsQuery() with the File stuff, still not able to get title, but I can get FileName which is good enough
    – lovejotd
    Commented Aug 20, 2014 at 18:07
  • Tyler, glad this helped you :) Commented Aug 20, 2014 at 18:13
  • 1
    Just a small note, I think the clue here is Scope="RecursiveAll" attribute on the View tag, I guess the actual items are subelements of the files or something, hence the need of recursive
    – eirikb
    Commented Jan 6, 2015 at 13:39
1

This is a document library, and libraries don't follow the same conventions as regular lists with regards to the contents of the Title field.

For a simple solution, you should find what you're looking for if you just use oListItem.get_item('FileLeafRef') as Vadim suggests.

See below for some other useful info, but in summary when I run into something like this I try investigating what is being returned from the list and double checking what field names are being used in the response... There are a few cases, such as this, where title isn't really the field you want (another example is a list created from a spreadsheet or database)

Also: something fun -- null is the actual default value for 'Title' on documents, so it was actually giving you the 'correct' result! Silly computers...


If you're still reading, I'll now explain how to inspect JSOM objects!

You can inspect the SP.ListItem objects that the the JSOM returns in your favorite browser dev tools (I like Chrome, but it doesn't really matter...)

So fire up a page where you can get a client context and run the first part of your script (you can paste it directly into the javascript console to manipulate the variables at the page level.)

var clientContext = new SP.ClientContext('/team');
var oList = clientContext.get_web().get_lists().getByTitle('KML');

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Leq><FieldRef Name=\'ID\'/><ValueType=\'Number\'>100</Value></Leq></Where></Query><RowLimit>50</RowLimit></View>');
var collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);
clientContext.executeQueryAsync();

Note I didn't provide any handlers like I would in a production script, because I'm going to manipulate the variables manually below...

Now in your JavaScript console, you can fetch all the public fields for an item by entering the command:

collListItem.getItemAtIndex(0).get_fieldValues()

You should see an object result that when you expand it should show you all the public fields that you can get with the listItem.get_item('itemName') function

EDIT: Simplified considerably thanks to input from Vadim on a public function (get_fieldValues) that I overlooked ;)

3
  • 1
    +1 for an nice explanation how to retrieve list item values. Though there is more simple way of accessing items values (field name/value). Instead of internal $m_dict object, you could use public FieldValues property for that purpose, for example: item.get_fieldValues() ;) Commented Aug 20, 2014 at 18:39
  • 1
    @VadimGremyachev huh -- that is super helpful, here I was rooting around through js-sort-of-private variables! I'll ammend my answer since that is better in nearly every way
    – John-M
    Commented Aug 20, 2014 at 18:47
  • I am not surprised to see this is also the answer... just wasn't sure how to get title if title isn't the title... There is a lot of good information here about debugging
    – lovejotd
    Commented Aug 20, 2014 at 18:52
0

What columns do you have added to the default view for the library? I've seen issues like this before when I had forgotten to add the columns I wanted to the default view. It seems unlikely Title wouldn't be in there, though...

I also saw a similar SO question where the .load function uses an extra argument:

clientContext.load(collListItem, "Include(Title)");

You might want to try that out as well, though honestly I've never used that second argument before.

2
  • I have tried that, and yes title is in the default view, neither of those worked...
    – lovejotd
    Commented Aug 19, 2014 at 14:20
  • Also you know that title is in the default view, because if title isnt there in the query that returns, you get an error instead of just a null value
    – lovejotd
    Commented Aug 20, 2014 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.