How delete all Items of SharePoint List using REST API?

Delete all Items of SharePoint List using REST API:

. Use the below code to delete items of list more than 5000 items at time.

var listname = "Company";//SharePoint list Name
var resultData = []; // variable (array) is used for storing list items
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listname+"')/items?$top=5000"; //SP list URL or REST API;
function fetchDataFromSPList(){
    $.ajax({
        url: url,  
        method: "GET",  
        headers: {  
            "Accept": "application/json; odata=verbose"  
        },
        success: function(data){
            resultData = resultData.concat(data.d.results);
            if (data.d.__next != undefined) {
                url = data.d.__next;
                fetchDataFromSPList();
            }else{
               resultData.forEach(function(d){
                    // you can also add some condition here to delete particular data from list
                    deleteSPListItems(listtName, d.ID, function(state,message){
                        console.log(state);// it will show you the deleted item as number of true value if true(8000) means 8000 items deleted from list, if it is False(8000) means some error is coming to delete
                    });
               });
            } 
        },
        error: function(error){
           // error 
            console.error(error);
        }
    });
}
fetchDataFromSPList();

function deleteSPListItems(listname,itemId,callBackToBegin){
    $.ajax({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+listname+"')/items("+itemId+")",  
        type: "POST",  
        async: false,  
        headers: {  
            "Accept": "application/json;odata=verbose",    
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "If-Match": "*",
            "X-Http-Method": "DELETE"
        },  
        success: function(data) {  
            callBackToBegin(true,'Item deleted successfully');
        },  
        error: function(data) {
            console.error(data);//console the error messages as object
            callBackToBegin(false,'Error: Failed to delete');  
        }  
    });
}

Output:

true 6500 //6500 items deleted from list Company

Comments

Popular posts from this blog

Get list item entity type full name of a SharePoint list using REST API

Get SharePoint list name by GUID

Get Current Web Logged In User of SharePoint Site in jQuery