SharePoint Dynamic CRUD Operations using Rest API
SharePoint Dynamic CRUD Operations using Rest API
Use the below code for dynamic CRUD operations. You can create CRUD.js file using the below code & call the crud operations from different places by passing different parameters.
//<<<<<<<<<<<<<<<<<<<<<<<< NOTE - Follow the below instructions to call the CURD Functions >>>>>>>>>>>>>>>>>>>>>>>>>
//-----------------createItem('ListName',['ColumnName1','ColumnName2',...],['Value1','Value2',...]);-------------
//Example: createItem('testlist',['Title','Name','Age'],['ABC','XYZ',10]);
//-----------------updateItem('ListName',itemID,['ColumnName1','ColumnName2',...],['Value1','Value2',...]);------
//Example: updateItem('testlist',31,['Title','Name','Age'],['ABC','XYZ',10]);
//-----------------deleteItem('ListName',itemID);----------------------------------------------------------------
//Example: deleteItem('testlist',1);
///----------------(Using ID) => readSingleItem('ListName',itemID,filterQuery);---------------------------------
///Example:Use done property to get data values
//var query = "?$select=Title,Name,Age";
//var succ = readSingleItem('testlist',34,query);
//succ.done(function(data){alert(data.d.Title)});
//-------------------(filter by column values) => readMultipleItems('ListName',filterQuery);-------------------
//Example:Use done property to get data values
//var query = "?$select=Title,Name,Age&$filter=Title eq 'ABC'"
//var succ = readMultipleItems('testlist',query);
//succ.done(function(data){ if(data.d.results[0] != null){alert(data.d.results[0].Title);} });
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< NOTE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//---------------------------------------------------------------CREATE NEW ITEM Function----------------------------------------------------------
function createItem(listName,columnNames,Values)
{
var deferred = $.Deferred();
var serverURL = _spPageContextInfo.webAbsoluteUrl;
var listUrl = String.format("{0}/_api/web/lists/GetByTitle('"+listName+"')/items",serverURL);
getItemTypeForListName(listName).done(
function(ListItemEntityTypeFullName)
{
var items = { '__metadata': {'type': ListItemEntityTypeFullName} }; //here it will bind metadata and below we are binding coulumn values
if(columnNames.length == Values.length)
{
for(var i=0;i<columnNames.length;i++)
{
items[columnNames[i]] = (Values[i] != '')? Values[i]:null;
}
}
else
{
alert("Please Provide Equal number of ColumnNames & Values for Create Item function!");
return;
}
$.ajax({
url: listUrl,
type: "POST",
data: JSON.stringify(items),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data){
//alert("Item added successfully!");
deferred.resolve();
},
error: function(err){
alert('error '+ err);
deferred.reject();
}
});
}).fail(function(error)
{
alert('error '+ err);
deferred.reject();
});
return deferred.promise();
}
//---------------------------------------------------------------UPDATE ITEMS Function----------------------------------------------------------
function updateItem(listName,itemID,columnNames,Values)
{
var deferred = $.Deferred();
var serverURL = _spPageContextInfo.webAbsoluteUrl;
var listUrl = String.format("{0}/_api/web/lists/GetByTitle('"+listName+"')/getItemByStringId("+itemID+")",serverURL);
getItemTypeForListName(listName).done(
function(ListItemEntityTypeFullName)
{
var items = { '__metadata': {'type': ListItemEntityTypeFullName} }; //here it will bind metadata and below we are binding coulumn values
if(columnNames.length == Values.length)
{
for(var i=0;i<columnNames.length;i++)
{
items[columnNames[i]] = (Values[i] != '')? Values[i]:null;
}
}
else
{
alert("Please Provide Equal number of ColumnNames & Values for Update Item function!");
return;
}
$.ajax({
url: listUrl,
type: "POST",
data: JSON.stringify(items),
headers: {
"Content-Type": "application/json;odata=verbose",
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-Http-Method": "PATCH",
"IF-MATCH": "*"
},
success: function(data){
//alert("Data Added Successfully!");
deferred.resolve();
},
error: function(err){
alert('error '+ err);
deferred.reject();
}
});
}).fail(function(error)
{
alert('error '+ err);
deferred.reject();
});
return deferred.promise();
}
//---------------------------------------------------------------READ ITEMS Function----------------------------------------------------------
function readSingleItem(listName,itemID,query)
{
var deferred = $.Deferred();
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
//var filterValue = "YourFilterValue";
var listURL = String.format("{0}/_api/web/lists/getbytitle('"+listName+"')/getItemByStringId("+itemID+")"+query,serverUrl);
$.ajax({
url: listURL,
type: "GET",
headers: {"Accept": "application/json;odata=verbose"},
cache: false,
success: function(data){
deferred.resolve(data);
},
error: function(err){
alert('error '+ err);
deferred.reject();
}
});
return deferred.promise();
}
//---------------------------------------------------------------READ ITEMS Function----------------------------------------------------------
function readMultipleItems(listName,query)
{
var deferred = $.Deferred();
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
//var filterValue = "YourFilterValue";
var listURL = String.format("{0}/_api/web/lists/getbytitle('"+listName+"')/items"+query,serverUrl);
$.ajax({
url: listURL,
type: "GET",
headers: {"Accept": "application/json;odata=verbose"},
cache: false,
success: function(data){
deferred.resolve(data);
},
error: function(err){
alert('error '+ err);
deferred.reject();
}
});
return deferred.promise();
}
//---------------------------------------------------------------DELETE ITEM Function----------------------------------------------------------
function deleteItem(listName,itemID)
{
var deferred = $.Deferred();
if((itemID != null) && (itemID !=''))
{
//alert('Your are going to delete this ID : '+ itemID);
//code for delete record
var serverURL = _spPageContextInfo.webAbsoluteUrl;
var listUrl = String.format("{0}/_api/web/lists/GetByTitle('"+listName+"')/items("+itemID+")",serverURL);
$.ajax({
url: listUrl,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"If-Match": "*"
},
success: function(data){
//alert("Item deleted successfully!");
deferred.resolve();
},
error: function(err){
alert('error '+ err);
deferred.reject();
}
});
}
return deferred.promise();
}
//--------------Other Supporting funcitons for CURD Start----------------------
//below 2 functions used for getting ListItemEntityTypeFullName that is used in metta data
function getItemTypeForListName(listTitle)
{
return executeJson({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName",
method: 'GET'
}).then(function(data){return data.d.ListItemEntityTypeFullName;});
}
function executeJson(options)
{
var headers = options.headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: options.method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(options.method == "POST") {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}
//--------------Other Supporting funcitons for CURD End----------------------
Comments
Post a Comment