Hello friends, in this article we will learn how to write and use jquery generic functions for REST API.

Scenario

You are writing a large code in jQuery where multiple Rest calls will be triggered to perform CRUD operation on the SharePoint list. To minimize the code length and performance, you are asked to write a single generic function to get the list data. You will call the same function to get the data from a different list.

Quick answer


//Module is for myGenericModule.
var myGenericModule = (function() {
 
    //private global variable
    var OPTIONS = {};
    var RESPONCE;

    var _init = function(options) {
        OPTIONS = options || [];

        if (options.isTrue == undefined) {
            OPTIONS.isTrue = true;
        } else {
            OPTIONS.isTrue = options.isTrue
        }
        RESPONCE = [];
    };

    //public generic function to get SP list items
    var GetItems = function getItems(options, callback, failure) {
        _init(options);
        getAllItems(function(results) {
            callback(results)
        }, function(error) {
            failure(error)
        });
    }

    //Retrieve list items
    //Private function
    function getAllItems(callback, failure) {
        $.ajax({
            url: OPTIONS.RequestURL,
            type: "GET",
            async: OPTIONS.isTrue,
            data: OPTIONS.InputData,
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function(data) {
                callback(data.d.results);
            },
            error: function(error) {
                failure(JSON.stringify(error));
            }
        });
    }

    return {
        GetItems: GetItems
    };

})();
//End of myGenericModule

//Example of calling GetItems method
var options = {};
options.RequestURL = _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Lists/GetByTitle('TopNavigation')/Items?$top=4999&$orderby=Id desc";
options.InputData = {
    $select: "Title,ParentLink/Title,URL,DisplayOrder,IsActive,OpenInNewWindow",
    $expand: "ParentLink" // lookup or User column
};
myGenericModule.GetItems(options, function(data) {
        console.log(data)
    },
    function(error) {
        console.log(error);
    });