Thursday, October 23, 2014

Updating SharePoint List items with SharePoint’s REST API in JavaScript

Greg Ostrowski

I previously wrote about how to get SharePoint list items using SharePoint’s REST API using ajax and javascript. Today we’re going to expand on that and add in functionality to update an item. Since we were previously working with a task list, the next logical functionality to add is a way to complete your tasks.

Picking up from last time, we start off our code the same way: Initialize by getting the user’s ID and then generate the REST request. When we get the results this time, though, we’ll be adding in a button for each item to mark the task as complete. We also bind a function to each of these markers which will trigger the code to update the item as ‘Complete’ to SharePoint’s database. We also move our drawing code into its own function so we can redraw the table after we successfully update an item.

//Upon Receiving Task List data, we set as our module's _task list .

//We then iterate through each task and add to a table which we then insert into our container defined in _options.container

function createTaskView(results, listName) {

    _tasks = results.d.results;



    drawTable();

}



function drawTable() {

    var table = $("<table style='width: 100%;'>" +

                        "<tr>" +

                            "<th>Title</th>" +

                            "<th>Due Date</th>" +

                            "<th>Status</th>" +

                            "<th></th>" +

                        "</tr>" +

                  "</table>");

    $.each(_tasks, function (index, task) {

        var tr = '<tr>' +

                   '<td>' + task.Title + '</td>' +

                   '<td>' + new Date(item.DueDate).toLocaleDateString() + '</td>' +

                   '<td>' + task.Status + '</td>' +

                   '<td><a href="javascript:;" data-id="' + task.Id +'" class="complete-task">x</a>' +

                '</tr>';

        table.append(tr);

    });

    $(_options.container).html(table);

    registerJQueryBinds(); //set up our binds so we can complete a task

}





//jQuery Binds

function registerJQueryBinds () {

	//grabs the data-id from the delete button so we know which task item to remove

	$(".complete-task").click(function() {

		updateListItem(getTaskItemById($(this).data("id")));

	});       

}

Now that we have the UI elements in place, we need the code to send the request to update the task item. This ajax request will have more to it in regards to headers and metadata on the item, but we need to abide by SharePoint’s rules for this to work. To reduce the amount of data we’re sending over in our request, we create a new object with only the information we need, in this case some metadata for our item and the field we’re changing with its updated value.

//Get a task object with id and list type of given parameters

function getTaskItemById(id) {

    var obj = {};

    _tasks.some(function (item) {

        if (item.ID === id) {

            obj = item;

            return;

        }

    });

    return obj;

}



//Function updates the list item to have a status of 'Completed'

function updateListItem (item) {

    //give item updated values before sending to Sharepoint List

    var sendItem = { "__metadata": { "type": item.__metadata.type } };

    sendItem['Status'] = 'Completed'; 

   

    $.ajax({

        url: item.__metadata.uri,

        type: "POST",

        contentType: "application/json;odata=verbose",

        data: JSON.stringify(sendItem),

        headers: {

            "Accept": "application/json;odata=verbose",

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

            "X-HTTP-Method": "MERGE",

            "If-Match": item.__metadata.etag

        },

        success: function (data) {

            console.log("Update Successful");

            _tasks.splice(_tasks.indexOf(getTaskItemById(itemId)), 1); //remove completed task

            drawTable(); //redraw our table as we only want to see uncompleted tasks

        },

        error: function (msg) {

            console.log(msg);

        }

    });

}

There you have it. Your own customized task list ready to be checked off and updated. Now if you want to get fancy, implement this with Knockout.js or another javascript library with object binding!

Full code can be found here.

Loading Next Article