Search This Blog

Friday, November 27, 2015

CRUD operations using SPServices

SPServices is a JQuery library which interacts with SharePoint web services. It is a script based technology which allows us to talk to SharePoint through its web services. 

The syntax is pretty simple, similar like JQuery and other scripting libraries. I have shown below the sample examples to achieve the CRUD operations using SPServices.

Get All the items from the list based on the condition using GetListItems

function ProcessData(xData)
{
  $("#content").html('');
  var ulTag=$('<ul style="list-style:square;"></ul>');  
  $(xData.responseXML).SPFilterNode("z:row").each(function() 
  {  
    var liTag=$("<li></li>").append($(this).attr("ows_Title"))
    ulTag.append(liTag);
  });
  $("#content").append(ulTag);    
}

$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Announcements",
    CAMLQuery: "<Query><Where><IsNotNull><FieldRef Name='Expires' /></IsNotNull></Where></Query>",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Expires' /><FieldRef Name='Body' /></ViewFields>",
    completefunc: ProcessData
    });   
    
});   

Delete All the items from the list using SPUpdateMultipleListItems

function DeleteAllItemsFromList()
  {
    $.SPServices.SPUpdateMultipleListItems({
    listName: "Announcements",
    CAMLQuery: "<Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where></Query>",
    batchCmd: "Delete"});
  }

Add item to a list using UpdateListItems

function AddItemsToList(title,content)
  { 
   $.SPServices({
   operation: 'UpdateListItems',
   listName: "Announcements",
   updates: '<Batch OnError="Continue">' + 
             '<Method ID="1" Cmd="New">' +
             '<Field Name="Title">'+ title +'</Field>' +
             '<Field Name="Body">'+ content +'</Field>' +
    '</Method>' +
             '</Batch>',
   completefunc: function(xData, Status)
        {}});  
  }

Update item in a list using UpdateListitems

$function UpdateListItem(itemID)
  { 
    $().SPServices({
    operation: 'UpdateListItems',
    async: false,
    listName: "Announcements", 
    updates: '<Batch OnError="Continue">' + 
             '<Method ID="1" Cmd="Update">' +
      '<Field Name="ID">' + itemID + '</Field>' + //Specifying the item id is very important here
             '<Field Name="Body">'+content+'</Field>' +
      '</Method>' +
             '</Batch>',
    completefunc: function(xData, Status)
    {}
   });  
 }
 
 


No comments:

Post a Comment