To retrieve more than 5,000 records from a SharePoint list using JavaScript and CAML query, you'll need to implement pagination, as SharePoint imposes a threshold limit of 5,000 items per request. Here is a sample approach to achieve this:
- Initialize Variables:
- Set up the necessary variables and configurations.
- Define the CAML query.
- Create a Function to Fetch Items:
- Use the REST API to fetch items.
- Implement pagination by using the
ListItemCollectionPositionNext
property.
- Combine Results:
- Aggregate results from each paginated request.
Here’s a JavaScript code snippet to help you get started:
const siteUrl = "https://your-sharepoint-site-url";
const listName = "YourListName";
const camlQuery = `
<View>
<Query>
<Where>
<!-- Your CAML query conditions go here -->
</Where>
</Query>
</View>`;
let allItems = [];
let listItemCollectionPosition = null;
function getListItems() {
return new Promise((resolve, reject) => {
const queryUrl = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/getitems`;
const requestBody = {
query: {
__metadata: { type: "SP.CamlQuery" },
ViewXml: camlQuery,
ListItemCollectionPosition: listItemCollectionPosition
}
};
$.ajax({
url: queryUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(requestBody),
success: function (data) {
const results = data.d.results;
allItems = allItems.concat(results);
listItemCollectionPosition = data.d.ListItemCollectionPositionNext;
if (listItemCollectionPosition) {
getListItems().then(resolve).catch(reject);
} else {
resolve(allItems);
}
},
error: function (error) {
reject(error);
}
});
});
}
getListItems()
.then((items) => {
console.log("All items retrieved:", items);
})
.catch((error) => {
console.error("Error retrieving items:", error);
});
Explanation
- Variables Initialization:
-
siteUrl
: URL of your SharePoint site. -
listName
: Name of the SharePoint list you want to retrieve items from. -
camlQuery
: The CAML query to filter items.
-
- Function
getListItems
:- Makes an AJAX POST request to fetch list items using the REST API.
- Uses
ListItemCollectionPositionNext
to handle pagination. - Aggregates all items into the
allItems
array.
- Recursion and Promise Handling:
- The function calls itself recursively until all pages of items are fetched.
- Uses Promises to handle asynchronous operations.
This script should be run in the context of a SharePoint page or a custom application page where jQuery is available. Adjust the CAML query to fit your specific filtering needs.