how to loop through item id and update items via CSOM

Iron Contributor

Here is my snippet code below.My aim is to simply loop through item ids and update the list in batches. I need help with using CSOM to do this I need this as currently when i send a batch of over 800 items i get timeout. Thanks in Advance

 

var items;
var oList;
var oListItem
function getItemsToBeUpdated()
{

  $('#lblprogress').text("Updating items please wait.... ");
  $('#lblprogress').show();


    var siteUrl = '/sites/MySite';


    var clientContext = new SP.ClientContext(siteUrl);
    //var clientContext = new SP.ClientContext.get_current();
   
     oList = clientContext.get_web().get_lists().getByTitle('PTest');
   
 var camlQuery = new SP.CamlQuery();
 camlQuery.set_viewXml('<View><Query></Query><RowLimit>100</RowLimit></View>');
    items = oList.getItems(camlQuery);
 clientContext.load(items);   
    clientContext.executeQueryAsync(updateMultipleListItemsSuccess, updateMultipleListItemsFailed);
        
   
   //This works but i need to send 17 items(using the itemid and then 13 items out of 30 for example etc..)
    for (var i = 1; i <= 17; i++) {

        this.oListItem = oList.getItemById(i);

        oListItem.set_item('Update', 'Force');

        oListItem.update();
       
        clientContext.executeQueryAsync(updateMultipleListItemsSuccess, updateMultipleListItemsFailed);
        

    }
   
    /*for (var i = 15; i <= 30; i++) {

        this.oListItem = oList.getItemById(i);

        oListItem.set_item('Force_x0020_Update', 'Force Update');

        oListItem.update();
       
        clientContext.executeQueryAsync(updateMultipleListItemsSuccess, updateMultipleListItemsFailed);
        

    }*/

}

//I can get the id here and use it onSucess but when i try updating here it doesnt work
function getID() {
  
   var itemEnumerator = items.getEnumerator();
    while(itemEnumerator.moveNext()){
        var item = itemEnumerator.get_current();
       
        // You now have the item you were looking for!
         console.log(item.get_item("ID"));
        
    }
  

}


function updateMultipleListItemsSuccess() {
  
   getID();

    $('#lblprogress').text("Items Updated Successfully");
    //alert('Items Updated');
    $('#reset').show();
   
  

}

    function updateMultipleListItemsFailed(sender, args)
    {   

     $('#lblprogress').hide();
     $('#lblerror').text('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     $('#reset').show();

    }

2 Replies
Patrick, try reducing the size of the batch to avoid the timeout issue. Try with for example 10 and then increase it if you need

Thanks Joel and I get that. My above code works.
I'm just to on how to approach this dynamically. If you look at my code above i'm not iterating through the item ids.

I need a something that can iterate through this ids and then send them for update in batches.

 

Cheers