7

I'm very new to REST and JSON, I want to copy list items from one list to another list in the same site on button click, both the lists are of same type but with different column names and they are 'Tasks' lists. I have the code to get the list items from a list and its below,

// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {

    // Executing our items via an ajax request
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (data) {
            failure(data);
        }
    });

}

I have the code to create an item in the list and its as below,

    function createListItem(webUrl,listName, itemProperties, success, failure) 
{    
 $.ajax(
{       
 url: webUrl + "/_vti_bin/listdata.svc/" + listName,   
     type: "POST",   
     processData: false,  
      contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: 
{   
         "Accept": "application/json;odata=verbose"
        }, 
       success: function (data) 
{           
 success(data.d);   
     },      
  error: function (data)
 {            
failure(data.responseJSON.error);    
    }  
  });
} 
 //Usage: create taskvar taskProperties = 
{   
 'TaskName': 'Order Approval',    'AssignedToId': 12};
 createListItem('https://contoso.sharepoint.com/project/','Tasks',taskProperties,function(task){ 
   console.log('Task' + task.TaskName + ' has been created');  
 }, 
 function(error){ 
   console.log(JSON.stringify(error)); 
 }); 

Now how to pass the required feild values from getListItems funtion to createListItem function, and how to make all these work on button click?

1
  • can you provide the complete code. I see that complete and failure method are not discussed in the sample
    – user812824
    Commented Dec 21, 2014 at 23:15

1 Answer 1

7

How to copy List Item using SharePoint 2013 REST

function getListItem(webUrl, listName,listItemId, complete, failure) {
    $.ajax({
        url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + listItemId + ")",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data.d); 
        },
        error: function (data) {
            failure(data);
        }
    });
}



function createListItem(webUrl,listName, itemProperties, complete, failure) 
{    
    $.ajax({       
       url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",   
       type: "POST",   
       processData: false,  
       contentType: "application/json;odata=verbose",
       data: JSON.stringify(itemProperties),
       headers: {   
          "Accept": "application/json;odata=verbose",
          "X-RequestDigest": $("#__REQUESTDIGEST").val()
       }, 
       success: function (data) {           
           complete(data.d);   
       },      
       error: function (data) {            
           failure(data.responseJSON.error);    
       }  
    });
} 



function copyListItem(webUrl,sourceListName,targetListName,listItemId,complete,failure)
{
    getListItem(webUrl,sourceListName,listItemId,
    function(sourceItem){
        //prepare item
        var copyItem = {};
        for (var propertyName in sourceItem) {
          if (sourceItem.hasOwnProperty(propertyName)) {
              if(sourceItem[propertyName] != null && sourceItem[propertyName].hasOwnProperty('__deferred'))  //exclude deffered objects 
              {
                  continue;
              }
              if(propertyName == 'GUID' || propertyName == 'ID' || propertyName == 'Id')   
              {
                 continue;
              }                  
              if(propertyName == '__metadata') {
                   var targetItemType = GetItemTypeForListName(targetListName);
                   copyItem['__metadata'] = { 'type': targetItemType };
              }
              else {
                  copyItem[propertyName] = sourceItem[propertyName]; 
              }    
          }
        }

        createListItem(webUrl,targetListName,copyItem,function(targetItem){
            complete(sourceItem,targetItem);
        },failure);
    },
    failure);   
}


function GetItemTypeForListName(name) {
    var itemType = "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    var encItemType = itemType.replace(' ','_x0020_');
    return encItemType;
}

Example: copy task item

var sourceListName = 'Tasks';
var sourceListItemId = 7;
var targetListName = 'Archive Tasks';
copyListItem(_spPageContextInfo.webAbsoluteUrl,sourceListName,targetListName,sourceListItemId,printInfo,logError);

function printInfo(sourceItem,targetItem)
{
    console.log(String.format('List Item has been copied from {0} to {1}',sourceListName,targetListName));  
}

function logError(sender,args)
{ 
    console.log(args.get_message());
}

Update

The following example demonstrates how to specify explicitly what fields to copy:

function copyListItem(webUrl,sourceListName,targetListName,listItemId,complete,failure)
{
    getListItem(webUrl,sourceListName,listItemId,
    function(sourceItem){
        //prepare item
        var copyItem = {};
        var targetItemType = GetItemTypeForListName(targetListName);
        copyItem['__metadata'] = { 'type': targetItemType };  //mandatory, do not remove metadata attribute!

        //specify explicitly what fields to copy here..
        //...
        copyItem['Title'] = sourceItem['Title']; //e.g. copy title

        createListItem(webUrl,targetListName,copyItem,function(targetItem){
            complete(sourceItem,targetItem);
        },failure);
    },
    failure);   
}

P.S. Use this copyListItem method instead of original one

8
  • I guess your code will copy all the column values of item '7' from 'Task' list to 'Archive Tasks' list, but I want only few column values from 'Task' list to be copied to 'Archive Tasks' list. Both lists have different column names. Commented Sep 11, 2014 at 10:03
  • That's right, source and target lists must have the same schema. See the updated answer for a case how to copy specific fields Commented Sep 11, 2014 at 10:11
  • In that case lists do not require to have the same schema.. Commented Sep 11, 2014 at 10:19
  • 1
    Your code worked like a charm, you are a rockstar :) Thanks a lot @Vadim :) Commented Sep 12, 2014 at 6:48
  • Karthik, glad it helped you! :) Commented Sep 12, 2014 at 6:49

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