Jackson Christopher
Jackson Christopher

Reputation: 101

Dynamic variable creation for multiple AJAX calls (SharePoint Online)

I use the following code to generate jquery datatables with data returned from SharePoint Online JSON on AJAX call. As My SPO list has over 50K rows and SPO has a 5000 view threshold limit, i make multiple ajax calls with REST API multiple date range filters and concat the results. The concatenated results are then passed as data source for the datatables plugin.

Kindly assist to shorten the following code for year variables and make the same to dynamically enter date ranges to make multiple AJAX calls. I'm guessing the process is to first read current year, generate first and last dates for current year, and then create new variables in descending order till 2005.

var results;
var allResults = [];

$(document).ready(function () {
    load();
});

function load() {
    var year2021 = $.ajax({    
        url: "SPO_Site/_api/web/lists/getbytitle('SPO_List')/items?$top=5000&$select=*,EncodedAbsUrl&$filter=(Date%20ge%20datetime%272020-12-31T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%272021-12-31T00:00:00.000Z%27)",    
        type: "GET", dataType: "json", headers: {"accept": "application/json;odata=verbose"},    
        success: mySuccHandler, error: myErrHandler}); 
    var year2020 = $.ajax({    
        url: "SPO_Site/_api/web/lists/getbytitle('SPO_List')/items?$top=5000&$select=*,EncodedAbsUrl&$filter=(Date%20ge%20datetime%272019-12-31T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%272020-12-31T00:00:00.000Z%27)",    
        type: "GET", dataType: "json", headers: {"accept": "application/json;odata=verbose"},    
        success: mySuccHandler, error: myErrHandler}); 
        
    .
    .
    .
    .
    .
    var year2005 = $.ajax({    
        url: "SPO_Site/_api/web/lists/getbytitle('SPO_List')/items?$top=5000&$select=*,EncodedAbsUrl&$filter=(Date%20ge%20datetime%272004-12-31T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%272005-12-31T00:00:00.000Z%27)",    
        type: "GET", dataType: "json", headers: {"accept": "application/json;odata=verbose"},    
        success: mySuccHandler, error: myErrHandler});          
    
    function mySuccHandler(a) {
        results = a.d.results;
        if (allResults.length > 0)
            allResults = allResults.concat(results);
        else
            allResults = results;        
    }
    function myErrHandler(data, errorCode, errorMessage) {
        console.log("Could not complete call: " + errorMessage);        
    };

   $.when(year2021, year2020, year2019, year2018, year2017, year2016, year2015, year2014, year2013, year2012, year2011, year2010, year2009, year2008, year2007, year2006, year2005).done(function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17){
    $('#table_id').DataTable({
        data:allResults,
        dom: 'Bfrtip',
        columns: [
                    { data: "Reg" },
                    { data: "EncodedAbsUrl",
                        "render": function (data, type, full)
                        {return '<a href="'+data+'" target="_blank">View</a>';}             
                    }
        ]
    });
   });  
};

Upvotes: 0

Views: 397

Answers (1)

Tomalak
Tomalak

Reputation: 338228

When your find yourself copy-pasting code, stop immediately and write a function and a loop.

When you find yourself copy-pasting code 15 times, you should have stopped 14 times ago to write a function and a loop.

The function:

function getItemsByYear(year, topRows=5000) {
    return $.ajax({
        type: "GET",
        headers: {
            Accept: "application/json;odata=verbose"
        },
        url: "SPO_Site/_api/web/lists/getbytitle('SPO_List')/items?" + $.param({
            $top: topRows,
            $select: '*,EncodedAbsUrl',
            $filter: `(Date ge datetime'${year}-01-01T00:00:00.000Z') and (Date lt datetime'${year + 1}-01-01T00:00:00.000Z')`
        }),
    })
    .then(function (response) {
        return response.d.results;
    })
    .fail(function (data, errorCode, errorMessage) {
        console.log("Could not complete call: " + errorMessage);        
    });
}

The loop:

$(function () {
    let currentYear = (new Date()).getFullYear(),
        requests = [];
    for (let counter = 0; counter < 15; counter++) {
        requests.push(getItemsByYear(currentYear - counter));
    }
    $.when.apply($, requests).done(function (itemsByYear) {
        $('#table_id').DataTable({
            data: itemsByYear.flat(),
            dom: 'Bfrtip',
            columns: [
                { data: "Reg" },
                { data: "EncodedAbsUrl", "render": function (data, type, full)
                    {return '<a href="'+data+'" target="_blank">View</a>';}             
                }
            ]
        });
    });
});  

Upvotes: 1

Related Questions