Read Publishing Image column in SharePoint using Rest Api and jQuery

Scenario

In this article, we are going to write a function to read the Publishing Column named 'BackgroundImage' from a SharePoint list. Learn how to get Publishing Column value using rest api and jquery in SharePoint. This method works for SharePoint 2013, 2016, 2019 and SharePoint Online.

Quick answer

function getPublishingImage(listname, id) {
    var publishingImage = '';
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
        method: 'GET',
        headers: {
            Accept: 'application/json; odata=verbose'
        },
        success: function (data, request) {
            debugger;
            // List item retrieved. Fetch the Publishing Image.
            var publishingImageUri = data.d.results[0].FieldValuesAsHtml.__deferred.uri;
            // Query SharePoint
            $.ajax({
                url: publishingImageUri,
                method: 'GET',
                headers: {
                    Accept: 'application/json; odata=verbose'
                },
                success: function (data, request) {
                    var regexpression = /<img.*?src="(.*?)"/
                    publishingImage = regexpression.exec(data.d.BackgroundImage)[1].toString();
                }
            });
        }
    });
    // Return the Publishing Image html
    return publishingImage;
};

Usage

If your list internal name is BackgroundList and you want to fetch the publishing image value for item with ID 10, then you can call the function as below:

getPublishingImage('BackgroundList', 10)

Post a Comment

0 Comments