Monday, November 2, 2015

CRUD Operations using JSOM

Add :- 

function Add() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title
    var itemCreateInfo = new SP.ListItemCreationInformation();

    var oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', 'Value'); //Title is the field and Value is the value for field
    oListItem.update();

    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data ADDED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot ADD');
    };

};

Update :- 
function Update() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title

    var oListItem = oList.getItemById(1);//Get the list item by id
    oListItem.set_item('Title', 'New Value');
    oListItem.update();
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data UPDATED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot UPDATE');
    };
};

Delete :-

function Delete() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title

    var oListItem = oList.getItemById(1);//Get the list item by id
   oListItem.deleteObject();
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data DELETED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot DELETE');
    };
};

No comments:

Post a Comment