March 19, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

Retrieve SharePoint list items using JavaScript

In this article, I will describe a simple use of SP.JS file to retrieve data from a SharePoint list and display the items in a certain way.

In this scenario, I have a list of FAQs as a custom list (ID, Title, Answer, Image…etc).

I needed to pull the items from the list and append them into Div in a SharePoint Page, applying the right CSS styles and adding some fancy stuffs (images and so on).

Here are the steps to follow :

1- Create (if needed) your list

2- Fill the rows (items).

3- Create a new SharePoint Page

4- Switch to edit mode (if not already in edit mode)

5- Insert a Content Editor WebPart

6- Inlcude the script.

 

The Script

This is 100% client side script which will use SP.JS library to load the list items, loop over them and append them to a page DIV.

 

In this part of the script, I Check If the SP.JS has been loaded properly, and I create a new instance of the ClientContext, I also create an instance of my list FAQs.

var clientContext;
var website;

// Make sure the SharePoint script file 'sp.js' is loaded before your
// code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

// Create an instance of the current context.
function sharePointReady() {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('FAQs');

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

    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded), 
        Function.createDelegate(this, this.onQueryFailed)
    ); 
}
PS: I use CAML query to get 10 rows and I attach two different functions for the onQuerySucceede and OnQueryFailed.
Please note that the 1st bloc of code checks for the SP.JS and waits until it has fully loaded.
These are the two functions that will be called on success or failure.
If the script runs property, the OnQuerySucceeded will loop over each item and calls the GetLine function to get the HTML content for that specific line, and append it to the Content div.
However, if something goes wrong, an error message will be shown.
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var FAQLine = GetLine(oListItem.get_item('Title'),oListItem.get_item('Answer'),oListItem.get_item('Created'));
        
        $('#Content').append(FAQLine);
    }

}

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

 

GetLine takes the parameters (Question, Answer and CreateDate), and put them in a nice HTML code.

function GetLine(Question, Answer, CreateDate)
{
    var Content='<div>';
    Content+='    <img src="https://cdn1.iconfinder.com/data/icons/all_google_icons_symbols_by_carlosjj-du/128/question-y.png" style="max-height:48px;float:left;padding:10px;"/><h3>'+Question+'</h3><p>'+Answer+'</h4>';
    Content+='<span class="badge badge-pill badge-success pull-right">'+CreateDate+'</span>';
    Content+='    </div>';
    return Content;
}

 

The final script should look like this:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"/> 

<script>
var clientContext;
var website;

// Make sure the SharePoint script file 'sp.js' is loaded before your
// code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

// Create an instance of the current context.
function sharePointReady() {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('FAQs');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' + 
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query>' + 
        '<RowLimit>10</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();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var FAQLine = GetLine(oListItem.get_item('Title'),oListItem.get_item('Answer'),oListItem.get_item('Created'));
        
        $('#Content').append(FAQLine);
    }

}

function GetLine(Question, Answer, CreateDate)
{
    var Content='<div style="margin-bottom:30px;">';
    Content+='    <h4><img src="https://cdn1.iconfinder.com/data/icons/all_google_icons_symbols_by_carlosjj-du/128/question-y.png" style="max-height:48px;float:left;padding:10px;"/>'+Question+'</h4><p>'+Answer+'</h4>';
    Content+='    </div>';
    return Content;
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + 
        '\n' + args.get_stackTrace());
}
</script> 
<div id="Content"> 

</div>