Accessing All Items in SharePoint Lists with Display Templates

I am on a mission to retrieve every single item from all lists within a SharePoint site. Despite my efforts, the resources I have come across explain how to fetch all lists or all items from a list, not every item in all lists within a site context.

My code is provided below and while I can successfully obtain all lists, my challenge lies in retrieving the items, and not just from the last list (as it seems to be doing when tested in the console - this updated version may instead result in null errors due to recent changes).

var allInfo = "";

        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAllListsAndItems);

        function getAllListsAndItems() {

            var context = new SP.ClientContext('https://mysites.sprcompanies.com/personal/cnorman/charpractice/');
            var web = context.get_web();
            var lists = web.get_lists();

            context.load(lists);

            context.executeQueryAsync(onQuerySucceeded, onQueryFailed);

            function onQuerySucceeded(sender, args) {            

                var listEnumerator = lists.getEnumerator();

                while (listEnumerator.moveNext()) {
                    var list = listEnumerator.get_current();                    
                    allInfo += " List: " + list.get_title() + "\n";

                    if (list.get_itemCount() > 0) {

                        var query = new SP.CamlQuery();
                        query.set_viewXml('<View></View>');
                        var items = list.getItems(query);

                        context.load(items);

                        context.executeQueryAsync(onSuccess, onFail);

                        function onSuccess(sender, args) {

                            var itemsEnumerator = items.getEnumerator();

                            while (itemsEnumerator.moveNext()) {
                                var item = itemsEnumerator.get_current(); 
                            }      

                        }

                        function onFail(sender, args) {
                            console.log('Request on items failed. ' + args.get_message() + '\n' + args.get_stackTrace());
                        }
                    }      
                }

                console.log(allInfo);
            }

            function onQueryFailed(sender, args) {
                console.log('Request on lists failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            } 
        }

The issue area appears to be here:

var itemsEnumerator = items.getEnumerator();

    while (itemsEnumerator.moveNext()) {
        var item = itemsEnumerator.get_current(); 
    } 

Initially, I attempted to append to allInfo, but it kept generating 'not initialized' errors. I assumed that I was not loading the items correctly, but testing in the console revealed the item collection objects were displaying, leading me to believe it relates to the above segment.

Could using a for loop to cycle through the items solve this? I only require the titles of each item. Even after trying both a for and a for in, errors persist. Hence, it appears the problem lies in how I am accessing each item (perhaps using incorrect properties). Thank you for your assistance!

Edit:

Incorporating this into the item onSuccess block instead:

if (items.get_item("Title") == null) {
    items.get_data().forEach(function(item) {     
        console.log(item.get_item('URL').get_description()); 
    }); 
}

else {
    items.get_data().forEach(function(item) {
        console.log(item.get_item('Title')); 
    });
}  

Both options retrieve the 'title' of an item regardless of whether it is a standard item or a link item. However, it solely gathers items from the last list and repeats them multiple times rather than traversing through every list.

Answer №1

For those curious about my process in finding the answer:

        var allInfo = "";
        var listsArray = [];
        var itemsArray = [];


        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAllListsAndItems);

        function getAllListsAndItems() {

            var context = new SP.ClientContext(SiteURL);
            var web = context.get_web();
            var lists = web.get_lists();

            context.load(lists);

            context.executeQueryAsync(onQuerySuccess, onQueryFailure);

            function onQuerySuccess(sender, args) {            

                var listEnumerator = lists.getEnumerator();

                while (listEnumerator.moveNext()) {
                    var list = listEnumerator.get_current();                    
                    listsArray.push(list.get_title());      
                }

                for (var i = 0; i < listsArray.length; i++) {

                    var query = new SP.CamlQuery();
                    query.set_viewXml('<View></View>');

                    itemsArray[i] = lists.getByTitle(listsArray[i]).getItems(query);

                    itemsArray.push(itemsArray[i]);

                    context.load(itemsArray[i]);
                }   

                context.executeQueryAsync(onSuccess, onFailure);

                function onSuccess(sender, args) {

                    for (var i = 0; i < itemsArray.length; i++) {

                        if (listsArray[i] != "Master Page Gallery") {

                            allInfo += " List: " + listsArray[i] + "\n";

                            itemsArray[i].get_data().forEach(function(item) {

                                if (item.get_item("Title") == null) {
                                    allInfo += " \t Item: " + item.get_item('URL').get_description() + "\n";
                                }

                                else if (item.get_item("Title") != null) {
                                    allInfo += " \t Item: " + item.get_item("Title") + "\n";
                                }

                                else {
                                    console.log("Something's wrong with this one.");
                                }

                            });
                        }
                    }                                

                    console.log(allInfo);  
                }

                function onFailure(sender, args) {
                    console.log('Request on items failed. ' + args.get_message() + '\n' + args.get_stackTrace());
                }             
            }

            function onQueryFailure(sender, args) {
                console.log('Request on lists failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }  
        }

Essentially, I had to store each loaded list in an array and then iterate through them individually to fetch items. Initially, looping through did not work as expected because it only captured the last list. This resulted in a structured output like this:

List
     Item
     Item
     ...
List
     Item
     Item
     ...
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enclose each instance of "Rs." with <span class="someClass">

I'm facing an issue with the currency symbol "Rs." appearing in multiple places on my website. I want to enclose every instance of this text within <span class="WebRupee">. However, if it's already wrapped in <span class="WebRupee">, ...

Is JavaScript utilizing Non-blocking I/O at the operating system level to enable AJAX functionality?

Given that Javascript operates as a single threaded process and AJAX functions asynchronously, the question arises: How does this happen? Is it possible that at the operating system level, the JS engine is responsible for making non-blocking I/O calls fo ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

The function currentTime is ineffective when attempting to stream audio through an http connection

Currently, I am implementing audio streaming through HTTP. To load the audio, I have incorporated the following code snippet. var audio = new Audio("http://example.com/get/stream/1/wav"); function seek(time){ audio.currentTime = time; } The browser h ...

Trouble with activating dropdown toggle feature in Bootstrap 5

I recently upgraded to Bootstrap 5 and now my code is not functioning properly. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria- controls="navbarCollaps ...

Conceal the input field prior to making a selection from the dropdown menu

I have implemented a drop-down menu for selecting dependencies, similar to how it functions in JSFiddle. $('#user_time_zone').on('change', function() { dateCalender = $(this).val(); if (dateCalender == 'Single Date') { ...

Integrating the HTML form with the CRUD functionalities

After building a backend application with JavaScript, NodeJS, ExpressJS, and MongoDB that utilizes basic CRUD operations, I am now unsure of how to direct the form submissions to the database. Additionally, I am curious about how to allow users to access ...

Utilizing arrays dynamically to generate data for a bar chart display in JavaScript

I'm currently working on generating a bar stack graph using the chart.js JavaScript library. My JavaScript array contains the following data: 0: {labels: "01/01/2020 00:00:00", data: 7433, category: "A"} 1: {labels: "01/01/2020 00:00:00", data: 774, ...

Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation. Currently, the JSON data is loaded via a mock server with th ...

Issues with form rendering in a Vue.js component

I have recently started learning vue.js and I'm trying to create a basic form using the materializecss framework within a component. The form requires this jQuery snippet to function: $(document).ready(function() { M.updateTextFields(); }); ...

React: Conceal additional elements once there are over three elements in each section

React: I am trying to create a menu with submenus. My goal is to calculate the number of submenus and if it goes over 3, hide the additional submenus. Below is the code snippet for counting the elements: export default function App() { const ElementRef ...

reloading a URL dynamically using an array in JavaScript

I need assistance with a Chrome extension code. The goal is to have it check the page that initially loads, and if it matches my website st.mywebsite.com, execute the specified code. Currently, it does not perform this check and runs on every loaded page ...

"Troubleshooting a Javascript guessing game that isn't functioning with a do-

I have been working on a JavaScript and HTML guessing game, but unfortunately, it's not functioning as expected with the following requirements: The game should take input from the user (three attempts allowed). After entering the number, it should c ...

Obtaining an array of weeks for the previous two months from the current date using JavaScript

Looking to generate a list of weeks for the past two months using JavaScript. Any suggestions on how to accomplish this task would be greatly appreciated. [ { "week_start": "8/01/2016", "week_end": "8/06/2016" }, { "w ...

Transform the object into JSON while excluding specific (private) attributes

I recently started using dean edwards base.js for organizing my program into objects. I must say, base.js is truly amazing! But now I have a question that doesn't require prior knowledge of base.js to answer. Within one of my objects, I have a proper ...

Interactive button with jQuery that toggles between clicked and unclicked states, automatically reverting to unclicked when clicked elsewhere on the page

I am trying to create a button that changes its appearance when clicked, and returns to its normal state if clicked again or if the user clicks outside of it. Here is the JavaScript code I have written: if($('#taskbar-start').hasClass('ta ...

Steps to invoke controller through ajax and transmit $_POST variables

I am trying to make an AJAX call to a controller in order to save data into a database. Once the data is saved, I want to display it in a dropdown list. However, I am facing some issues and not sure what to do next. Below is the code snippet from my view ...

Is there a way to implement this code to filter every column in the grid?

I have been using this code in my grid view, but it only filters one column of the grid. Now I want to modify the code to filter multiple columns. I tried implementing a loop, but it seems like the code is not working correctly. Is there a way to adjust t ...

Accessing JSON fields containing accents in JavaScript

I am encountering an issue with the JSON file below: { "foo supé": 10 } My attempt is to extract and log the value of the field "foo supé" into the console using the code snippet provided: <!DOCTYPE html> <html> <s ...