Friday 14 August 2015

CRUD Operation with REST API in SharePoint 2013

Here , for example we take a custom List named 'TestList' with two columns .
(1) Title
(2) Designation

Below is the js file code snipped which have the CRUD operation functions.




// handle the click event of the button

$(document).ready( function(){


$("#btnSubmit").click(function(){

//alert ("Site" + _spPageContextInfo.siteAbsoluteUrl  );

//alert( "Web" +   _spPageContextInfo.webAbsoluteUrl );

CreateNew();

}  );


// Upadte Button


$("#btnUpdate").click( function() {

Update();

});



$("#btnDelete").click( function(){

deleteItem(54);
}
);



});



//===============   Start Create Item ============================================ //



// occurs when a user clicks the create button
function CreateNew() {
    var listName = "TestList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, newItemTitle) ;
}

// CREATE Operation
// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in.
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function CreateListItemWithDetails(listName, newItemTitle) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle,
        "Designation" : 'Project Manager'
       
    };

 alert(JSON.stringify(item));


    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
             success();
           
            //alert('success');
        },
        error: function (data) {
            failure();
         
           //alert('Error');
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}



//function success() { alert("New Item has been created successfully."); } // getListItems("TestList");}


function failure() {
     alert("Ooops, an error occured. Please try again.");
 }



//===============   End Create Item ============================================ //





// ============================================== Start Update Item  =================================================== //



// occurs when a user clicks the update button
function Update() {
    var listName = "TestList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "55"; // Update Item Id here
    var title = "New Updated Title";
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Update Operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function updateListItem(itemId, listName, siteUrl, title, success, failure) {


//alert('In UpdatelistItem');

    var itemType = GetItemTypeForListName(listName);

    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    getListItemWithId(itemId, listName, siteUrl, function (data) {
   
    alert('Update success function is called ..!!!'+ data.__metadata.uri );
   
    alert("Etag is  : " + data.d.__metadata.etag );
   
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
               // "If-Match": "*"
            },
            success: function (data) {
               // success(data);
               
                alert ('success');
               
            },
            error: function (data) {
                //failure(data);
               
                alert ('error');
            }
        });
    }, function (data) {
        failure(data);
    });
}


function getListItemWithId(itemId, listName, siteurl, success, failure) {

//alert('In GetListItemWithId');


    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
   // alert(url);
   
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
             
// alert('Item is fetched ..!!!'+ JSON.stringify(data.d.results[0]) );              
  success(data.d.results[0]);              
             
            }
            else {
               // failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            //failure(data);
           
            alert('Item not found ...!!!');
           
        }
    });
}




// ============================================== End Update Item  =================================================== //







// ============================= Start Delete Item ================================================================= //




function deleteItem(id) {
alert('Delete Function is called ..!!!');

var DeleteItemUrl = "/_api/Web/Lists/GetByTitle('TestList')/getItemById('"+id+"')";
    $.ajax({      
        url: _spPageContextInfo.webAbsoluteUrl + DeleteItemUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": "*",
            "X-Http-Method": "DELETE"
        },
        success: function (data) {
           alert('Delete Successfully ..!!!');
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}












// ============================= End Delete Item ================================================================= //


function getListItems(listname ) {
// Getting our list items
$.ajax({
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/Items",
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/Items",

method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
 
  var items = data.d.results;
 
  var html = "<table>";
 
  for (var i = 0; i < items.length; i++)
  {          
//alert(items[i].Id+ " : " + items[i].Title);      

html = html + "<tr> <td>"+items[i].Id+"</td> <td>"+items[i].Title+"</td> </tr>";

}

html = html+ "</table>" ;

//$("#resultarea").append(html);



$("#resultarea").html(html);



},
error: function (data) {
alert('In Error..'+JSON.stringify(data)); }
});
};


function complete(data) {
alert("Completed successfully."  );



var jsonObject = JSON.parse(data.body);

alert(jsonObject );

var results = jsonObject.d.results;

for (var i = 0; i < results.length; i++) {

           alert('In for loop ..!!!' +  results[i].Title);

        }


}
function failure(data) {
alert("Operation failed.");
}

No comments:

Post a Comment