Hi in this article am going to explain how to perform list crud operations using JSOM in Sharepoint hosted apps.
Upon creating of sharepoint hosted app we will get created with Default.aspx page we will write all designing code (HTML) here.
And in App.js file we will write business logic using jsom.
To Read List Items Using JSOM:-
var hostWebUrl;
var appWebUrl;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
GetListItems();
}
function GetListItems() {
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web(); //Get the Web
var list = web.get_lists().getByTitle("SampleList"); //Get the List
var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List
query.set_viewXml('<View><RowLimit></RowLimit>100</View>');
var items = list.getItems(query);
ctx.load(list); //Retrieves the properties of a client object from the server.
ctx.load(items);
var table = $("#tblalldata");
var innerHtml = "<tr><th>ID</th><th>Name</th><th>Location</th><th>Edit</th><th>Delete</th></tr>";
//Execute the Query Asynchronously
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var itemInfo = '';
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var currentListItem = enumerator.get_current();
innerHtml += "<tr><td>" + currentListItem.get_item('ID') + "</td><td><input style='display:none;' type='text' value='' id='txtname" + currentListItem.get_item('ID') + "' /> " +
"<span id='stname" + currentListItem.get_item('ID') + "'>" + currentListItem.get_item('Name') + "</span></td><td><input style='display:none;' type='text' value='' id='txtloc" + currentListItem.get_item('ID') + "' />" +
"<span id='stloc" + currentListItem.get_item('ID') + "'>" + currentListItem.get_item('Location') + "</span></td><td><input type='button' value='Edit' class='btnEditRow' id='" + currentListItem.get_item('ID') + "' />" +
"<input type='button' style='display:none;' value='Update' class='btnUpdateRow' id='U" + currentListItem.get_item('ID') + "' />" +
"<input type='button' style='display:none;' value='Cancel' class='btnCancel' id='C" + currentListItem.get_item('ID') + "' /></td>" +
"<td><input type='button' value='Delete' class='btnDeleteRow' id='D" + currentListItem.get_item('ID') + "' /></td></tr>";
}
table.html(innerHtml);
}),
Function.createDelegate(this, fail)
);
}
function success() {
//$("#dvMessage").text("Operation Completed Successfully");
alert('Operation Completed Successfully');
}
function fail() {
//$("#dvMessage").text("Operation failed " + arguments[1].get_message());
alert('Operation Failed' + arguments[1].get_message());
}
function manageQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) {
return singleParam[1];
}
}
}
To Create List Item:-
Place this code in document.ready() function.
Here while getting all list items i created create button in that upon clicking item getting into editable mode enter the values and click on create.
$("#btn-add").on('click', function () {
createListItem();
GetListItems()
$("#tblEditmode").hide();
$("#btn-new").show();
});
function createListItem() {
var name = document.getElementById('EmpName').value;
var loc = document.getElementById('EmpLoc').value;
if (name != "" && name != null && loc != "" && loc != null) {
var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web(); //Get the Site
var list = web.get_lists().getByTitle("SampleList"); //Get the List based upon the Title
var listCreationInformation = new SP.ListItemCreationInformation(); //Object for creating Item in the List
var listItem = list.addItem(listCreationInformation);
listItem.set_item("Name", $("#EmpName").val());
listItem.set_item("Location", $("#EmpLoc").val());
listItem.update(); //Update the List Item
ctx.load(listItem);
//Execute the batch Asynchronously
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
}
else {
alert('Please enter Name and Location');
}
}
To Edit List Item:-
By Edit button in the table it gets editable mode.
$("body").on('click', '.btnEditRow', function () {
var this_itemId = $(this).attr('id');
$(this).hide();
EditListItem(this_itemId);
});
function EditListItem(itemId) {
//$("#tblEditmode").show();
$("#txtname" + itemId).show();
$("#txtloc" + itemId).show();
$("#U" + itemId).show();
$("#C" + itemId).show();
$("#stname" + itemId).hide();
$("#stloc" + itemId).hide();
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web();
var list = web.get_lists().getByTitle("SampleList");
ctx.load(list);
itemUpdate = list.getItemById(itemId);
ctx.load(itemUpdate);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
//Display the Data into the TextBoxes
//$("#EmpId").val(itemUpdate.get_item('ID'));
$("#txtname" + itemId).val(itemUpdate.get_item('Name'));
$("#txtloc" + itemId).val(itemUpdate.get_item('Location'));
}),
Function.createDelegate(this, fail)
);
}
To Update List Item:-
Whenever we edit the item need to update to latest values so we can find there update button upon clicking that item will get updated.
$("body").on('click', '.btnUpdateRow', function () {
var this_itemId = $(this).attr('id');
$(this).hide();
updateListItem(this_itemId);
GetListItems()
});
function updateListItem(itemId) {
while (itemId.charAt(0) === 'U')
itemId = itemId.substr(1);
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web();
var list = web.get_lists().getByTitle("SampleList");
ctx.load(list);
//var cur_item = document.getElementById('EmpId').value;
var itemUpdate = list.getItemById(itemId);
ctx.load(itemUpdate);
itemUpdate.set_item('Name', $("#txtname" + itemId).val());
itemUpdate.set_item('Location', $("#txtloc" + itemId).val());
itemUpdate.update();
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
$("#stname" + itemId).show();
$("#stloc" + itemId).show();
$("#" + itemId).show();
$("#txtname" + itemId).hide();
$("#txtloc" + itemId).hide();
}
Upon creating of sharepoint hosted app we will get created with Default.aspx page we will write all designing code (HTML) here.
And in App.js file we will write business logic using jsom.
To Read List Items Using JSOM:-
var hostWebUrl;
var appWebUrl;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
GetListItems();
}
function GetListItems() {
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web(); //Get the Web
var list = web.get_lists().getByTitle("SampleList"); //Get the List
var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List
query.set_viewXml('<View><RowLimit></RowLimit>100</View>');
var items = list.getItems(query);
ctx.load(list); //Retrieves the properties of a client object from the server.
ctx.load(items);
var table = $("#tblalldata");
var innerHtml = "<tr><th>ID</th><th>Name</th><th>Location</th><th>Edit</th><th>Delete</th></tr>";
//Execute the Query Asynchronously
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var itemInfo = '';
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var currentListItem = enumerator.get_current();
innerHtml += "<tr><td>" + currentListItem.get_item('ID') + "</td><td><input style='display:none;' type='text' value='' id='txtname" + currentListItem.get_item('ID') + "' /> " +
"<span id='stname" + currentListItem.get_item('ID') + "'>" + currentListItem.get_item('Name') + "</span></td><td><input style='display:none;' type='text' value='' id='txtloc" + currentListItem.get_item('ID') + "' />" +
"<span id='stloc" + currentListItem.get_item('ID') + "'>" + currentListItem.get_item('Location') + "</span></td><td><input type='button' value='Edit' class='btnEditRow' id='" + currentListItem.get_item('ID') + "' />" +
"<input type='button' style='display:none;' value='Update' class='btnUpdateRow' id='U" + currentListItem.get_item('ID') + "' />" +
"<input type='button' style='display:none;' value='Cancel' class='btnCancel' id='C" + currentListItem.get_item('ID') + "' /></td>" +
"<td><input type='button' value='Delete' class='btnDeleteRow' id='D" + currentListItem.get_item('ID') + "' /></td></tr>";
}
table.html(innerHtml);
}),
Function.createDelegate(this, fail)
);
}
function success() {
//$("#dvMessage").text("Operation Completed Successfully");
alert('Operation Completed Successfully');
}
function fail() {
//$("#dvMessage").text("Operation failed " + arguments[1].get_message());
alert('Operation Failed' + arguments[1].get_message());
}
function manageQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) {
return singleParam[1];
}
}
}
To Create List Item:-
Place this code in document.ready() function.
Here while getting all list items i created create button in that upon clicking item getting into editable mode enter the values and click on create.
$("#btn-add").on('click', function () {
createListItem();
GetListItems()
$("#tblEditmode").hide();
$("#btn-new").show();
});
function createListItem() {
var name = document.getElementById('EmpName').value;
var loc = document.getElementById('EmpLoc').value;
if (name != "" && name != null && loc != "" && loc != null) {
var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web(); //Get the Site
var list = web.get_lists().getByTitle("SampleList"); //Get the List based upon the Title
var listCreationInformation = new SP.ListItemCreationInformation(); //Object for creating Item in the List
var listItem = list.addItem(listCreationInformation);
listItem.set_item("Name", $("#EmpName").val());
listItem.set_item("Location", $("#EmpLoc").val());
listItem.update(); //Update the List Item
ctx.load(listItem);
//Execute the batch Asynchronously
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
}
else {
alert('Please enter Name and Location');
}
}
To Edit List Item:-
By Edit button in the table it gets editable mode.
$("body").on('click', '.btnEditRow', function () {
var this_itemId = $(this).attr('id');
$(this).hide();
EditListItem(this_itemId);
});
function EditListItem(itemId) {
//$("#tblEditmode").show();
$("#txtname" + itemId).show();
$("#txtloc" + itemId).show();
$("#U" + itemId).show();
$("#C" + itemId).show();
$("#stname" + itemId).hide();
$("#stloc" + itemId).hide();
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web();
var list = web.get_lists().getByTitle("SampleList");
ctx.load(list);
itemUpdate = list.getItemById(itemId);
ctx.load(itemUpdate);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
//Display the Data into the TextBoxes
//$("#EmpId").val(itemUpdate.get_item('ID'));
$("#txtname" + itemId).val(itemUpdate.get_item('Name'));
$("#txtloc" + itemId).val(itemUpdate.get_item('Location'));
}),
Function.createDelegate(this, fail)
);
}
To Update List Item:-
Whenever we edit the item need to update to latest values so we can find there update button upon clicking that item will get updated.
$("body").on('click', '.btnUpdateRow', function () {
var this_itemId = $(this).attr('id');
$(this).hide();
updateListItem(this_itemId);
GetListItems()
});
function updateListItem(itemId) {
while (itemId.charAt(0) === 'U')
itemId = itemId.substr(1);
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web();
var list = web.get_lists().getByTitle("SampleList");
ctx.load(list);
//var cur_item = document.getElementById('EmpId').value;
var itemUpdate = list.getItemById(itemId);
ctx.load(itemUpdate);
itemUpdate.set_item('Name', $("#txtname" + itemId).val());
itemUpdate.set_item('Location', $("#txtloc" + itemId).val());
itemUpdate.update();
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
$("#stname" + itemId).show();
$("#stloc" + itemId).show();
$("#" + itemId).show();
$("#txtname" + itemId).hide();
$("#txtloc" + itemId).hide();
}
To Delete List Item:-
Click on Delete button to delete item in table.
$("body").on('click', '.btnDeleteRow', function () {
var this_itemId = $(this).attr('id');
deleteListItem(this_itemId);
GetListItems()
});
function deleteListItem(itemId) {
while (itemId.charAt(0) === 'D')
itemId = itemId.substr(1);
var ctx = new SP.ClientContext(appWebUrl);
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web();
var list = web.get_lists().getByTitle("SampleList");
ctx.load(list);
listItemToUpdate = list.getItemById(itemId);
ctx.load(listItemToUpdate);
listItemToUpdate.deleteObject();
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
}
If you don't want update the data after editing the item just click on cancel to revert back/
$("body").on('click', '.btnCancel', function () {
var this_itemId = $(this).attr('id');
$(this).hide();
GetListItems()
});
Thank You.........