Error Looping Occurs when Recursively Calling RestAPI to Render Data on Datatables

I am facing the challenge of exceeding the 5000 view limit in SharePoint Online and need to implement recursive RestAPI calls to overcome this limitation. The code I have currently goes into a loop after generating the initial 5000 entries from my SharePoint list, which contains a total of only 8800 entries.

My goal is to fetch the first batch of 5000 entries followed by the remaining 3800 entries using recursive calls and then display the combined data in Jquery Datatables.

$(document).ready(function() {
        var table = $('#table_id').DataTable({
            "pageLength": 100,
            "dom": 'Bfrtip',
            "buttons": [searchBuilder, copy],
            "aoColumns": [{"mData": "Created"}, {"mData": "EncodedAbsUrl"}]
        });
        
var response = response || [];

var listURL = "SPO_Site/_api/web/lists/getbytitle('List_Name')/items?$top=5000&$select=Created,EncodedAbsUrl";
GetListItemsRecursive(listURL);

function GetListItemsRecursive() {
    $.ajax({
        url: listURL,
        type: "GET",
        dataType: "json",
        headers: {
            "accept": "application/json;odata=verbose"
        },
        success: mySuccHandler,
        error: myErrHandler
    });
}

function mySuccHandler(data) {
    response = response.concat(data.d.results);
    console.log(data);
    if (data.d.__next) {GetListItemsRecursive(data.d.__next);}
    try {table.rows.add(response).draw();} 
    catch (e) {alert(e.message);}
}

function myErrHandler(data, errMessage) {alert("Error");}
});

Answer №1

Here is a sample code snippet for your reference:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
<script>
    $(document).ready(function () {
    
        var response = response || [];

        var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('testn')/items?$top=5000&$select=ID,Title";
        GetListItemsRecursive(listURL);

        function GetListItemsRecursive(listURL) {
            $.ajax({
                url: listURL,
                type: "GET",
                dataType: "json",
                async: false,
                headers: {
                    "accept": "application/json;odata=verbose"
                },
                success: mySuccHandler,
                error: myErrHandler
            });
        }

        function mySuccHandler(data) {

            console.log(data)
            response = response.concat(data.d.results.map(e=>[e.ID,e.Title]));
            
            console.log(response);
            if (data.d.__next) { GetListItemsRecursive(data.d.__next); }
            // try { table.rows.add(response).draw(); }
            // catch (e) { alert(e.message); }

        }
        function myErrHandler() {

        }
        $('#table_id').DataTable({
                data: response,
                columns: [
                    { title: "ID" },
                    { title: "Title" }
                ]
            });
    })
</script>
<table id="table_id" class="display"></table>

This code sample has been tested and works correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the language of the submit and reset button text based on a variable

I'm facing a simple question but I'm stuck right now... and I was hoping someone could assist me. My issue is as follows: I need to switch the values of two buttons, reset and submit, from Greek to English and vice versa based on a variable retri ...

What is the best way to refresh an array in Swift after the user clicks on "Play Again"?

Below is the code for a quiz app that asks users to guess the capital of a given state. There is an array called placeArray that stores the questions, and each time a question is asked, removeAtIndex() is called to avoid repetition. This results in placeAr ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

Running JavaScript on Django Page via URL without refreshing the page

I have developed a webpage that is capable of loading specific JavaScript packages. www.mySite.com By entering JavaScript commands into the browser console, I can easily interact with them. Let's consider the following simple example: alert(' ...

What is the best way to populate a remote html page in real-time according to user input?

Is it feasible to use only JavaScript and HTML to allow users to select from a list of options and then print a page that includes a checklist of their selections? ...

To successfully use Router.use(), you must provide a valid middleware function. How can we resolve this issue of passing undefined as

I have developed a CRUD application using node.js and now I need to incorporate another node project as a microservice. To send HTTP requests to the other node project, I am utilizing the axios npm module. However, when I run the code, I keep encountering ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

Issues arise when trying to access JSON data that has been added to an array using the JavaScript .push method

I am encountering an issue where I cannot retrieve values from an array after storing it in a variable outside of the getJSON function. The response in JSON format looks like this: [ { "Book_ID": "1", "Book_Name": "Computer Architectu ...

Obtain JSON data instead of XML data from a web service through Ajax with the option 'contentType' set to 'false'

Upon making an AJAX call to send an image file to one of my web service (.asmx) methods, I encountered a problem where the web service returns XML instead of JSON. This issue arose because I needed to set the contentType to false, in order to successfully ...

Exploring variations in error handling for JavaScript promises in Node.js depending on whether the error is synchronous or asynchronous

Exploring the nuances of promise error handling for thrown errors and exceptions in the promise executor, particularly in comparison to reject, within a node.js context. Differences in handling between reject and throw/exceptions are evident. Some source ...

Vuetify's personalized date selection tool

Utilizing Vuetify's v-date-picker in multiple components can result in code repetition. To address this, I decided to create a custom <custom-date-picker /> component that can be used wherever needed. This child component should em ...

A comparison between the if statement and switch statement in JavaScript

Let's dive into a challenging scenario for those who consider themselves experts in JavaScript, particularly with switch and if statements. Here is how it typically works: var a = 1; if (a == 1) alert("true"); This is just a basic example. Now, let& ...

Updating Element Value in Python Using JS and Selenium

Hello, everyone. I'm new to coding and seeking some help regarding a problem I encountered with using 2captcha for my Python web scraping automation. Upon running the script, I receive the captcha token from 2captcha as instructed in their API documen ...

What is the process of transforming a JSON string into a JavaScript date object?

{"date":"Thu Dec 06 14:56:01 IST 2012"} Is it possible to convert this JSON string into a JavaScript date object? ...

The "Network" tab in Firefox does not display AJAX requests made from a content script

I'm currently working on my first web extension, but I've encountered some difficulties with web requests. Whenever I make an AJAX request or any other type of request, it doesn't seem to appear in the "Network" tab. I've been monitori ...

The dialogue within the map function is not functioning properly

In my state, I have saved data (objects) known as workitems. When these objects are mapped out to a table, everything functions correctly. However, upon trying to implement a Dialog feature with a button that allows users to view more information about a s ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

Transform CamelCase words into CamelCase naming conventions within Newtonsoft.Json

After upgrading to the latest version of Newtonsoft.Json (12.0.2), I discovered that the StringEnumConverter.CamelCaseText property had been deprecated. According to the StringEnumConverter class, "StringEnumConverter.CamelCaseText is obsolete. Set StringE ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

com.sun.istack.SAXException2: The context does not recognize class java.util.LinkedHashMap or any class in its inheritance hierarchy

A POST request is being sent to create a resource named ContentInstance. Resource: ContentInstance. // This code snippet was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 import java.math.BigInteger; impo ...