4

I want to delete all the contents of list using javascript

I tried

REST

jQuery.ajax({
    url: "/sites/hr/_api/lists/GetByTitle('Groups')/items?$filter Title neq x&$Top=20000",
    type: "DELETE",
    headers: {
        Accept: "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "IF-MATCH": "*"
    }       
})

and CSOM

var ctx = SP.ClientContext.get_current(),
   list = ctx.get_web().get_lists().getByTitle('MyList'),
   query = new SP.CamlQuery(),
   items = list.getItems(query);
ctx.load(items, "Include(Id)");
ctx.executeQueryAsync(function () {
    var enumerator = items.getEnumerator(),
        simpleArray = [];
    while (enumerator.moveNext()) {
        simpleArray.push(enumerator.get_current());
    }
    for (var s in simpleArray) {
        simpleArray[s].deleteObject();
    }
    ctx.executeQueryAsync();
});

Both don't seem to work

What is wrong with the snippets?

For the Rest I am getting 400 error but when I open the url its fetching restults

For the CSOM I don't get any errors but the items are not deleted

3 Answers 3

3

Try it as below:

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Groups')/items",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        var items = data.d.results;
        for(var item in items){
            var itemUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Groups')/getItemById(" + item.ID + ")";
            deleteItem(itemUrl);
        }
    },
    error: function (error) {
        console.log(JSON.stringify(error));
    }
});

function deleteItem(itemUrl) {
    $.ajax({
        url: itemUrl,
        type: "DELETE",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": "*"
        },
        success: function (data) {
            console.log("deleted item")
        },
        error: function (error) {
            console.log(JSON.stringify(error));
        }
    });
}

Using JSOM, you can delete multiple item in batch:

function deleteListItems() {

    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('TestList');


    for(var i = 0; i<= 100; i++){
        //assuming the IDs are available, else need some validation  
        var oListItem = oList.getItemById(i);  
        oListItem.deleteObject();
    }

    clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}

function onQuerySucceeded() {

    alert('Items Deleted');
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
deleteListItems();

Reference - Batch operations using JSOM

Using CAML query, you do it as below:

var clientContext = SP.ClientContext.get_current(); 
var customList = clientContext.get_web().get_lists().getByTitle('Test'); 
var itemColl; 

var camlQuery = new SP.CamlQuery(); 
    //set your caml query here
   camlQuery.set_viewXml( 
         '<View><Query><Where><Eq>' + 
           '<FieldRef Name=\'Title\'/><Value Type=\'Text\'>x</Value>' + 
         '</Eq></Where></Query></View>'); 
     itemColl = customList.getItems(camlQuery); 

clientContext.load(itemColl);

clientContext.executeQueryAsync(deleteitemColl, onGetitemCollFail);

function deleteitemColl() {

    var itemArray = new Array();
    var listItemEnumerator = itemColl.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var item = listItemEnumerator.get_current();
        itemArray.push(item);
    }

    var i;
    for (i = 0; i < itemArray.length; i++) {
        customList.getItemById(itemArray[i].get_id()).deleteObject();
    }

    clientContext.executeQueryAsync(onDeleteitemCollSuccess, onDeleteitemCollFail);
}

function onGetitemCollFail(sender, args) {
    console.log('Unable to get completed items. Error:' + args.get_message() + '\n' + args.get_stackTrace());
}

function onDeleteitemCollSuccess() {
    console.log('Completed orientations have been deleted.');    
}    

function onDeleteitemCollFail(sender, args) {
    console.log('Unable to delete completed items. Error:' + args.get_message() + '\n' + args.get_stackTrace());
}
4
  • Thanks any way to delete with one server hit? Commented Mar 31, 2017 at 8:59
  • Have updated answer, to delete multiple items using JSOM. Ensure that item id is available, else do a caml query and then use the above code to delete items Commented Mar 31, 2017 at 9:04
  • it throws an error Unable to delete completed items. Error:The request uses too many resources. the list has around 13K items Commented Mar 31, 2017 at 9:16
  • 1
    The ajax request will only fetch batches of 100. You can make it iterate through all items wrapping the GET request in a function (getData), and then call it from the succes part: if(data.d.__next) { url = data.d.__next; getData(); }
    – JJD
    Commented Mar 31, 2017 at 10:24
2

Deleting a list item using CSOM:

To delete a list item, call the DeleteObject() method on the object. The following example uses the GetItemById() method to return the second item from the list, and then deletes the item.

using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
 class DeleteListItem
  {
    static void Main()
    {   
        string siteUrl = "http://MyServer/sites/MySiteCollection";

        ClientContext clientContext = new ClientContext(siteUrl);
        SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
        ListItem oListItem = oList.GetItemById(2);

        oListItem.DeleteObject();

        clientContext.ExecuteQuery(); 
    }
  }
}

Reference:

JQuery

Deleting a list item using REST API:

function deleteListItem()  
{  
 $.ajax  
 ({  
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items(7)",  
    type: "POST",  
    headers:  
    {  
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
        "IF-MATCH": "*",  
        "X-HTTP-Method": "DELETE"  
    },  
    success: function(data, status, xhr)  
    {  
        retriveListItem();  
    },  
    error: function(xhr, status, error)  
    {  
        $("#ResultDiv").empty().text(data.responseJSON.error);  
    }  
 });  
}  

Reference:

How to delete list item in Parent site using REST API

How to delete list item using REST services

2

Delete all SharePoint ListItems using javascript SPServices library :

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices-2014.02.min.js"></script>
<script language="javascript" type="text/javascript">


function deleteListItems() {
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Groups", // List name
    CAMLViewFields: "<ViewFields><FieldRef Name='ID' /></ViewFields>",
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        var id = parseInt($(this).attr("ows_Id"));
        // Delete list item
        $().SPServices({
        operation: "UpdateListItems",
        async: false,
        listName: "Groups", // List Name
        batchCmd: "Delete",
        ID: id,
        completefunc: function(xData, Status) {
            console.log('List item has been deleted');
        }
        });
      });
    }
  });
}

</script>

Refrences:

1
  • var id = parseInt($(this).attr("ows_ID")); work for me .
    – alireza
    Commented Sep 27, 2018 at 6:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.