KnockoutJS SharePoint 2013 CRUD Operations using REST API

KnockoutJS SharePoint 2013 CRUD Operations using REST API.png

SharePoint expanded much in REST API from 2013 version onwards. Also, nowadays modern frameworks like angular, knockout are very much useful and powerful in web development.

With this I come up with blog which will showcase basic Create, Read, Update and Delete operations in SharePoint list. I have used knockout js as binding agent. Also knockout. Validation is used to validate data before submit. You can customize the files as per the needs of business.

I personally like to start with UI part so below is HTML required for our application.
HTML:

KnockoutJS SharePoint online CRUD Operations using REST API
KnockoutJS SharePoint online CRUD Operations using REST API

Above code shows standard input fields in html for first name and last name.
Below that will be tabular format to display data from SharePoint list.

JavaScript:

Read: Create Custom Tiles using HTML CSS and KnockoutJS in SharePoint 2013

I am using SharePoint REST API to get list data and perform other operations.



//load view model after documnet gets loaded

$(document).ready(function () {

mainFunction();

});

var modelInstance=null;

//Function to activate Knockout

function mainFunction() {

modelInstance = new crudViewModel();

modelInstance.errors = ko.validation.group(modelInstance); //for validation of fields

ko.applyBindings(modelInstance);

modelInstance.getEmpDetails();

}

//define view Model

var crudViewModel = function () {

var self = this;

var listName = “EmpDetails”;

self.Id = ko.observable();

self.firstName = ko.observable().extend({ required: “Please enter First name” });

self.lastName = ko.observable().extend({ required: “Please enter Last name” });

self.Employees = ko.observableArray();

self.displayStatus = ko.observable();

self.year = ko.observable(“”);

self.shouldShowMessage= ko.observable(false);

//Function to Read all Employees details

self.getEmpDetails = function(){

$.ajax({

url: _spPageContextInfo.siteAbsoluteUrl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items”,

type: “GET”,

headers: { “Accept”: “application/json;odata=verbose” },

success: function (data) {

self.Employees(data.d.results);//add employee details to observable

},

error: function (data) {

self.displayStatus(“Error in processing request ” + data.status);

}

});

};

//function to validate data such as blank values are not alllowed in input fields

self.validateAndSave=function(){

if(modelInstance.errors().length === 0){

self.addEmployee(); }

else{alert(“please check your details”);

modelInstance.errors.showAllMessages();

self.displayStatus(“Please fill all required details”);

}

};

//Function to add new employee details in list

self.addEmployee = function (){

self.shouldShowMessage(true);

var itemType = “SP.Data.EmpDetailsListItem”;

var emp = {

“__metadata”: { “type”: itemType },

“firstName”: self.firstName,

“lastName”: self.lastName

};

$.ajax({

url: _spPageContextInfo.siteAbsoluteUrl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items”,

type: “POST”,

contentType: “application/json;odata=verbose”,

data: ko.toJSON(emp),

headers: {

“Accept”: “application/json;odata=verbose”,

“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()

},

success: function (data) {

alert(“New Employee Created Successfully”);

self.getEmpDetails();//call to display again

},

error: function (data) {

self.displayStatus(“Error in processing request ” + data.status);

}

});

self.clear();

};

//Function to get Specific Employee details using its ID

function getEmpById (callback) {

var url = _spPageContextInfo.siteAbsoluteUrl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items(” + self.Id()+ “)”;

$.ajax({

url: url,

type: “GET”,

headers: { “Accept”: “application/json;odata=verbose” },

success: function (data) {

callback(data);

},

error: function (data) {

self.displayStatus(“Error in processing request”);

}

});

};

//Function to Update Category

self.updateEmpDetails = function () {

getEmpById(function (data) {

var itemType = “SP.Data.EmpDetailsListItem”;

var emp = {

“__metadata”: { “type”: itemType },

“firstName”: self.firstName,

“lastName”: self.lastName

};

$.ajax({

url: data.d.__metadata.uri,

type: “POST”,

contentType: “application/json;odata=verbose”,

data: ko.toJSON(emp),

headers: {

“Accept”: “application/json;odata=verbose”,

“X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),

“X-HTTP-Method”: “MERGE”,

“If-Match”: data.d.__metadata.etag

},

success: function (data) {

alert(“Employee details updated successfully”);

self.getEmpDetails();//call to display again

self.clear();

},

error: function (data) {

self.displayStatus(“Error in processing request ” + data.status + ” ” + data.statusCode);

}

});

});

};

//Function to Delete Employee details

self.deleteEmpDetails = function (emp) {

getEmpById(function (data) {

var itemType = “SP.Data.EmpDetailsListItem”;

var emp = {

“__metadata”: { “type”: itemType },

“firstName”: self.firstName,

“lastName”: self.lastName

};

$.ajax({

url: data.d.__metadata.uri,

type: “POST”,

contentType: “application/json;odata=verbose”,

data: ko.toJSON(emp),

headers: {

“Accept”: “application/json;odata=verbose”,

“X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),

“X-HTTP-Method”: “DELETE”,

“If-Match”: data.d.__metadata.etag

},

success: function (data) {

alert(“Employee details deleted successfully”);

self.getEmpDetails();//call to display again

self.clear();

},

error: function (data) {

self.displayStatus(“Error in processing request ” + data.status + ” ” + data.statusCode);

}

});

});

};

//Function to Select Employee used for Update and Delete

self.selectEmployee = function (emp) {

self.Id(emp.Id);

self.firstName(emp.firstName);

self.lastName(emp.lastName);

};

//Function to clear all fields

self.clear = function () {

self.displayStatus(“”);

self.Id(0);

self.firstName(“”);

self.lastName(“”);

};

};//End of view model

Finally add content editor web part on any page and refer html file from SharePoint.
End result will be as follows:

 

KnockoutJS SharePoint 2013 CRUD Operations using REST API
KnockoutJS SharePoint 2013 CRUD Operations using REST API

Add First Name and last name. Click on Create. Alert will be displayed that “New employee created.” To update and delete first click on table row. It will select employee and then click on update/delete which will perform action in list and will be displayed in UI as well.

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Prajkta Patil

I am a SharePoint Developer with 6+ years of experience working on a range of projects like building intranet, migrating SharePoint environment from older to latest versions,building Nintex/Designer workflows to develop business process. My skills and knowledge include: • SharePoint Development • Designer/Nintex workflows- design, development and support • C# and ASP.net development • HTML, CSS, jQuery • REST,spservices • PnP Powershell •knockout,angular frameworks • Sitecore development My current role is to develop intranet sites,workflows design,powerapp development. It allows me to deliver best solutions to business users.

View all posts by Prajkta Patil →