0

I have queried all of the lists within a subsite but need to filter based on criteria in the title.

I then need to display the filtered list contents. Is this possible if the list contents are not all the same?

Thank you in advance SP community!

This is what I have so far, it is not working:

<script type="text/javascript">
var siteUrl = 'https://myportal/mysite/mysubsite';

// Load the required SharePoint libraries.
$(document).ready(function () {

    // The js files are in a URL in the form:
    // web_url/_layouts/15/resource_file
    var scriptbase =  siteUrl  + "/_layouts/15/";

    // Load the js files and continue to
    // the execOperation function.
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js", execOperation);
        }
    );
});

// Function to execute basic operations.
function execOperation() {

    // Continue program flow here.
     retrieveWebSiteProperties(siteUrl);

}

function retrieveWebSiteProperties(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();
    this.listInfoCollection = clientContext.load(collList);

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

 function onQuerySucceeded(sender, args) {
    var listInfo = '';
    var listEnumerator = this.collList.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
       if(oList.get_title().indexOf("pro") !== -1){ //if title contains "pro"
       listInfo += 'Title: ' + oList.get_title() + ' Created: ' + 
oList.get_created().toString() + '\n';
            }
        }

        $("#chartArea").html(listInfo);

    }

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

</script>
3
  • Are you getting any error? Commented Dec 26, 2018 at 14:11
  • nope, console errors :/ just a blank page
    – seaandtea
    Commented Dec 26, 2018 at 14:31
  • See my answer below; it is possible that your code is not executing because of collisions w/ jQuery. Can you add a console.log somewhere in $().ready(...) to be sure it's running? Commented Dec 27, 2018 at 13:59

1 Answer 1

0

First- are you running this code on a page that inherits from a SharePoint master page? Or is your code "outside" of SharePoint? Also, are you using SharePoint Online or SharePoint Server? (For my examples below I'm using SP Server 2016).

I would suggest not using $(document).ready, because this can collide with SharePoint's own methods for delaying script execution (and leave you with no way of knowing in which order code will execute). Instead use _spBodyOnLoadFunctionNames.push() (Reference), which does a good job of delaying script execution until after the body loads.

Edit: the only SP native library you need here is SP.js which provides the ClientContext object. This library is automatically declared as a dependency early on in the Master Page: RegisterSod() is called on SP.js early in the master page

Since this call to RegisterSod() is already being made, we don't need to call it again; instead we can just go ahead and use SP.SOD.executeFunc() with a reference to 'sp.js', which ensures that that script is available before our code runs. This is actually simpler than my original solution, because you don't even need to specify where SP.js is located- SharePoint already knows, because of the earlier call to RegisterSod('SP.js'):

    SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
        // This will run after sp.js is loaded.
        retrieveWebSiteProperties(_spPageContextInfo.webAbsoluteUrl);
    });

I made some changes to your code and was successfully able to run it on my Dev farm. Here is my setup:

This is the output: Output from running the script in SharePoint

Reference for SP.SOD methods

Edit 2 You can also get List names & list items using REST. The idiom is actually a lot easier to use than JSOM, and it is very easy to implement with jQuery. This will not work as expected in SharePoint Online:

// Set the REST endpoint to use. 
// This one includes a filter to only return lists whose title includes "Site"
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists?$filter=substringof('Site', Title)";

// Create the AJAX request using jQuery. All you need to specify are the endpoint and the right headers to get back JSON
var request = jQuery.ajax({ url: url, headers: { "Accept": "Application/json;odata=nometadata" } });

// Use a .then() callback to do something with the data after it it returned by the server
request.then(
    function (d) {
        // For each result in the set of returned data
        d.value.forEach(
            function (i) {
                // Print the Title of the list to the console
                console.log(i.Title);
            });
    });
6
  • I replaced my $(document).ready function and my execOperation() function with your code but no luck :/ did I miss something?
    – seaandtea
    Commented Dec 27, 2018 at 14:58
  • Can you diagnose where the code is falling down using console.log()? I would suggest that if initialize() is firing that you try getting rid of the SP.SOD code and just try calling retrieveWebSiteProperties() immediately. Commented Dec 27, 2018 at 15:50
  • @Torybee I ran your code as a test and was able to get it to work. Please see my updated answer. Commented Dec 27, 2018 at 16:52
  • Thanks so much for your help, really insightful information you've provided. I used your code, (in a CEWP pointing to the html file) and still no luck. I am running this code on a page that inherits a master page, on SP 2013. The only other thing I've got in the HTML doc are these script links: <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" /> <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/> I don't currently see how but - could they be interfering?
    – seaandtea
    Commented Dec 27, 2018 at 18:34
  • Glad it's somewhat helpful / Sorry it's still not working. MicrosoftAjax is probably redundant- I'm pretty sure it was replaced by jQuery, unless you need it for a specific reason. I'm using jQuery-1.8.1 in my own farm, FWIW. At this point I would settle for just getting any kind of feedback in the console. Try putting a call to retrieveWebSiteProperties() inside a setTimeout() with a 5 or 10 second delay. If it doesn't work after 10 seconds of the page being fully loaded then the problem is not with the lazy-loading code or dependencies. Commented Dec 27, 2018 at 19:22

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.