CRUD on SharePoint list item using JQuery Deferred promise

Add new list item.
After new list item added, read all list items.

This demonstrates JavaScript promise in SharePoint context.

What is a Promise?

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

Learn more...

var deferred = $.Deferred();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var listName = "SPFx";

$(function(){   
    bindButtonClick();
});

function bindButtonClick(){
    $('#btnSubmit').on('click', function(){
        addListItem().then(function(data){
            getListData();
        });
    });
}

var addListItem = function(){
    var title = $('#txtTitle').val();   
    var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items";

    $.ajax({
        url: fullUrl,
        type: "POST",
        data: JSON.stringify({
            '__metadata': { 'type': 'SP.Data.SPFxListItem' },
            'Title': title           
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: onQuerySucceeded,
        error: onQueryFailed
    });

    return deferred.promise();
}

function onQuerySucceeded(sender, args){
    deferred.resolve(sender, args);   
}

function onQueryFailed(sender, args){
    deferred.reject(sender, args);   
}

function getListData(){
   
    var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items";

    $.ajax({
        url: fullUrl,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose"
        },
        success: onQuerySucceeded1,
        error: onQueryFailed1
    });
}

function onQuerySucceeded1(data){
    var listItemInfo = '';
    $.each(data.d.results, function (key, value){
        listItemInfo += "<li class='list-group-item'>" + value.Title + "</li>";
    });
    $("#divResult").html(listItemInfo);
}

function onQueryFailed1(){
    alert("Error!");
}

Comments

Popular posts from this blog

The all new Movie Central

Movie Central 4.0 (New Release in works)

How to install nVidia Optimus driver