Sunday, 21 August 2011

Add\Delete\Retrieve List items using Javascript Client object model SharePoint 2010


Lets look at an example to Add\Delete\Retrieve List items using Javascript Client object model SharePoint 2010

Adding a List item –

<script type=”text/javascript”>

function AddItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);

var listItemCreationInfo = new SP.ListItemCreationInformation();
var newItem = list.addItem(listItemCreationInfo);
newItem.set_item(‘Title’, ‘SPUser’);

newItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Added!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());
}

Delete an item -

function deleteItem(ItemId)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);
var itemToDelete = list.getItemById(ItemId);
itemToDelete.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Deleted!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());

}

Retriving List Items -

function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘Testlist’);
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, ‘Include(Title,Department)’);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var TextFiled = “”;
var ListEnumerator = this.allItems.getEnumerator();
while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
TextFiled += currentItem.get_item(‘Title’) + ‘-’ +currentItem.get_item(‘Department’) + ‘\n’;
}
alert(TextFiled);
}
function failed(sender, args) {
alert(“failed. Message:” + args.get_message());
}
</script>

Ads by Google

No comments:

Post a Comment