Create Retrieve Update and Delete SharePoint List Item using REST API and JQuery

In this article, I would like to show you utilizing SharePoint REST API and JQuery to Create, Retrieve, Update and Delete SharePoint list item.

Pre-Requisite

  • Reference to latest jquery.min.js
  • For this example purposes, create custom List called “MyList” with default “Title” column.

Create

// occurs when a user clicks the create button
function CreateNew() {
    var listName = "MyList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, newItemTitle, function () {
        alert("New Item has been created successfully.");
 }, function () {
     alert("Ooops, an error occured. Please try again.");
 });
}

// 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, webUrl, newItemTitle, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle
    };

    $.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(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

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

Retrieve Item

// READ SPECIFIC ITEM operation
// itemId: The id of the item to get
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function getListItemWithId(itemId, listName, siteurl, success, failure) {
    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
                success(data.d.results[0]);
            }
            else {
                failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            failure(data);
        }
    });
}

Retrieve All Items

// occurs when a user clicks the read button
function Read() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;

    getListItems(listName, url, function (data) {
        var items = data.d.results;

        // Add all the new items
        for (var i = 0; i < items.length; i++) {
            alert(items[i].Title + ":" + items[i].Id);
        }
    }, function (data) {
        alert("Ooops, an error occured. Please try again");
    });
}

// READ operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function getListItems(listName, siteurl, success, failure) {
    $.ajax({
        url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Update

// occurs when a user clicks the update button
function Update() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // 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) {
    var itemType = GetItemTypeForListName(listName);

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

    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.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.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }, function (data) {
        failure(data);
    });
}

Delete

// occurs when a user clicks the delete button
function Delete() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // Update Item ID here
    deleteListItem(itemId, listName, url, function () {
        alert("Item deleted successfully");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Delete Operation
// itemId: the id of the item to delete
// listName: The name of the list you want to delete the item from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function deleteListItem(itemId, listName, siteUrl, success, failure) {
    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    },
   function (data) {
       failure(data);
   });
}

Reference

Advertisements

Tagged: , , , , , , , , ,

25 thoughts on “Create Retrieve Update and Delete SharePoint List Item using REST API and JQuery

  1. SutoCom 02/23/2014 at 3:48 PM Reply
  2. Fernando Hunth 05/26/2014 at 8:24 PM Reply

    Change this alert(“New Item has been created successfully.”);]

    • tjenho 06/05/2014 at 5:03 AM Reply

      Thank you …
      Its updated now.

  3. Stephen Clement 07/02/2014 at 3:36 PM Reply

    Hi, this is a very helpful page and one of the only resources I could find on the topic. For some reason I am having an issue with the ajax used to post. I can run the scripts all the way up to that ajax call and then an error arises with no indication of what could have gone wrong. I am just trying to update a list item, but I also copied the code for the retrieval function since that was included in the update code. Thanks for this helpful code!

    • tjenho 07/03/2014 at 4:23 PM Reply

      Hi Stephen, thanks for looking into my code. Please change on error function inside ajax call to below, so you can see the error.

      error: function (err) {
      alert(JSON.stringify(err));
      }

      Hopefully it helps you to determine the issue and google from there.

      • Stephen Clement 07/09/2014 at 12:05 PM

        Thank You very much for your help. I have gotten the error and hopefully I will be able to figure it out from here. Very helpful article and comments!

  4. Stephen Clement 07/14/2014 at 2:55 PM Reply

    Hey, back again! This article has been very helpful in some work I am doing, but currently I have run into an issue. I want to be able to execute some of this code while logged into an account that may or may not have permissions to edit or add new items to the list in question. Is this possible?

  5. essjrnet 01/07/2015 at 6:37 PM Reply

    Can I create a list item using this script in a public site in sharepoint online? I can not insert an item in the list, sharepoint always returns me error 403 (forbidden).

    • tjenho 01/08/2015 at 11:34 AM Reply

      Hi, yes you can. I think you have to make sure few things:
      1. Ensure the user can add new item to the list (permission allowed)
      2. Compare item type result from GetItemTypeForListName function with item type from GET item from REST API.
      Thanks

  6. […] I have based this response and this post… […]

  7. CR Rollyson 04/24/2015 at 8:34 AM Reply

    Are you able to retrieve the page image associated with the list item where applicable using this setup?

  8. James Fox 06/30/2015 at 2:57 PM Reply

    Is it possible to create a pop up box where the user can fill in several categories with the create and update function? I can only figure out how to do one at a time.

    • tjenho 07/01/2015 at 6:58 AM Reply

      Sure can, you could build your input form using SP.UI.ModalDialog.showModalDialog and use my javascript function to complete your actions.

  9. malgoul2000 08/13/2015 at 4:46 AM Reply

    Nice Article, but I have question, how I can manage to list column in user interface page.

  10. […] Create Retrieve Update and Delete SharePoint List Item using REST API and JQuery | Tjen Sharepoint B… […]

  11. Faheem Zafar 02/08/2016 at 6:59 PM Reply

    nice one Tjen … concise and accurate

  12. girish chalke 05/03/2016 at 8:25 AM Reply

    Just add here that GetItemTypeForListName() may not return correct type if List name has any special characters in it. Either handle it or simply Return it as string using /ListItemEntityTypeFullName

    • tjenho 05/06/2016 at 10:46 AM Reply

      thanks for sharing your experience.

  13. abhisheksahayblog 05/18/2016 at 7:02 AM Reply

    Visit the below URL for Rest operations like GET and POST
    https://abhisheksahayblog.wordpress.com/

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: