Before reading this article, please look into the previous article to learn how to create a list in site and create a SharePoint hosted app in Visual Studio.

In this article, we will discuss from the third point onward, as we have already discussed the first two points in Part One.

  1. Create a List in Office 365 SharePoint Site
  2. Creation of Project using SharePoint Hosted App
  3. HTML code for User Interface
  4. Write Business logic for Insert, Update, Delete, Get data functionalities under App.js file.
  5. Deploy the Project
  6. Test the application.
HTML Code for User Interface

In default.aspx page, we will do some changes as mentioned below.

Write Business logic for Insert, Update, Delete, Get data functionalities under App.js file.

We are writing some methods for insert, update, delete, and get data and clear data operations.

Finally, the App.js code looks like below.

  1. 'use strict';
  2. var hostWebUrl;
  3. var appWebUrl;
  4. var listName = "Employee";
  5. ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");
  6. function initializePage() {
  7. var context = SP.ClientContext.get_current();
  8. var user = context.get_web().get_currentUser();
  9. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  10. $(document).ready(function () {
  11. GetEmployeeDetails();
  12. $("#btnCreate").on('click', function () {
  13. createEmployee();
  14. ClearData();
  15. });
  16. $("#btnUpdate").on('click', function () {
  17. UpdateEmployee();
  18. ClearData();
  19. });
  20. $("#btnClear").on('click', function () {
  21. ClearData();
  22. });
  23. $("#btnGet").on('click', function () {
  24. $('#empName').val("");
  25. $("#empSalary").val("");
  26. $("#tblAddress").val("");
  27. $("#tblEmployees").empty();
  28. GetEmployeeDetailsByID();
  29. });
  30. $("#btnDelete").on('click', function () {
  31. deleteEmployee();
  32. ClearData();
  33. });
  34. });
  35. function deleteEmployee() {
  36. var id = $("#empID").val();
  37. $.ajax
  38. ({
  39. url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + id + "')",
  40. type: "POST",
  41. headers:
  42. {
  43. "Accept": "application/json;odata=verbose",
  44. "Content-Type": "application/json;odata=verbose",
  45. "X-RequestDigest": $("#__REQUESTDIGEST").val(),
  46. "IF-MATCH": "*",
  47. "X-HTTP-Method": "DELETE"
  48. },
  49. success: function (data, status, xhr) {
  50. $("#tblEmployees").empty();
  51. GetEmployeeDetails();
  52. alert("Successfully record deleted");
  53. },
  54. error: function (xhr, status, error) {
  55. alert(JSON.stringify(error));
  56. }
  57. });
  58. }
  59. function ClearData() {
  60. $("#empID").val("");
  61. $('#empName').val("");
  62. $("#empSalary").val("");
  63. $("#empAddress").val("");
  64. }
  65. function GetEmployeeDetailsByID() {
  66. var idValue = $("#empID").val();
  67. $.ajax({
  68. url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + idValue + "')",
  69. type: "GET",
  70. headers: { "Accept": "application/json;odata=verbose" }, // return data format
  71. success: function (data) {
  72. $("#empName").val(data.d.Title);
  73. $("#empSalary").val(data.d.Salary);
  74. $("#empAddress").val(data.d.Address);
  75. $("#tblEmployees").empty();
  76. GetEmployeeDetails();
  77. },
  78. error: function (error) {
  79. alert(JSON.stringify(error));
  80. }
  81. });
  82. }
  83. function UpdateEmployee() {
  84. var id = $("#empID").val();
  85. $.ajax({
  86. url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + id + "')", // list item ID
  87. type: "POST",
  88. data: JSON.stringify
  89. ({
  90. __metadata:
  91. {
  92. type: "SP.Data.EmployeeListItem"
  93. },
  94. Title: $("#empName").val(),
  95. Salary: $("#empSalary").val(),
  96. Address: $("#empAddress").val()
  97. }),
  98. headers:
  99. {
  100. "Accept": "application/json;odata=verbose",
  101. "Content-Type": "application/json;odata=verbose",
  102. "X-RequestDigest": $("#__REQUESTDIGEST").val(),
  103. "IF-MATCH": "*",
  104. "X-HTTP-Method": "MERGE"
  105. },
  106. success: function (data, status, xhr) {
  107. $("#tblEmployees").empty();
  108. GetEmployeeDetails();
  109. alert("Date Updated Successfully");
  110. },
  111. error: function (xhr, status, error) {
  112. alert(JSON.stringify(error));
  113. }
  114. });
  115. }
  116. function createEmployee() {
  117. $.ajax({
  118. url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
  119. type: "POST",
  120. contentType: "application/json;odata=verbose",
  121. data: JSON.stringify
  122. ({
  123. __metadata:
  124. {
  125. type: "SP.Data.EmployeeListItem"
  126. },
  127. Title: $("#empName").val(),
  128. Salary: $("#empSalary").val(),
  129. Address: $("#empAddress").val()
  130. }),
  131. headers: {
  132. "Accept": "application/json;odata=verbose", // return data format
  133. "X-RequestDigest": $("#__REQUESTDIGEST").val()
  134. },
  135. success: function (data, status, xhr) {
  136. $("#tblEmployees").empty();
  137. GetEmployeeDetails();
  138. alert("Successfully Submitted");
  139. },
  140. error: function (xhr, status, error) {
  141. alert(JSON.stringify(error));
  142. }
  143. });
  144. }
  145. function GetEmployeeDetails() {
  146. $.ajax({
  147. url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID,Title,Salary,Address",
  148. type: "GET",
  149. headers: { "Accept": "application/json;odata=verbose" }, // return data format
  150. success: function (data) {
  151. //console.log(data.d.results);
  152. var table = $("#tblEmployees");
  153. var html = "<thead><tr><th>ID</<th><th>Name</th><th>Salary</th><th>Address</th></tr></thead>";
  154. for (var i = 0; i < data.d.results.length; i++) {
  155. var item = data.d.results[i];
  156. //$("#tblEmployees").append(item.Title + "\t" + item.Salary + "\t" + item.Address + "<br/>");
  157. html += "<tr><td>" + item.ID + "</td><td>" + item.Title + "</td><td>" + item.Salary + "</td><td>" + item.Address + "</td></tr>";
  158. }
  159. table.html(html);
  160. },
  161. error: function (error) {
  162. alert(JSON.stringify(error));
  163. }
  164. });
  165. }
  166. function manageQueryStringParameter(paramToRetrieve) {
  167. var params =
  168. document.URL.split("?")[1].split("&");
  169. var strParams = "";
  170. for (var i = 0; i < params.length; i = i + 1) {
  171. var singleParam = params[i].split("=");
  172. if (singleParam[0] == paramToRetrieve) {
  173. return singleParam[1];
  174. }
  175. }
  176. }
  177. // This function prepares, loads, and then executes a SharePoint query to get the current users information
  178. function getUserName() {
  179. context.load(user);
  180. context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
  181. }
  182. // This function is executed if the above call is successful
  183. // It replaces the contents of the 'message' element with the user name
  184. function onGetUserNameSuccess() {
  185. $('#message').text('Hello ' + user.get_title());
  186. }
  187. // This function is executed if the above call fails
  188. function onGetUserNameFail(sender, args) {
  189. alert('Failed to get user name. Error:' + args.get_message());
  190. }
  191. }
Deploy the Project

Right click on the solution and select the "Deploy" option.

SharePoint

Test the application

Here, we will test for "Submit" button.

Here, we have seen CRUD operations for REST API in SharePoint 2013. I am attaching the code here. Please test and let me know if you have any queries. We will see more on REST APIs in my upcoming article.