Friday, 21 September 2018

REST API code

<script src="https://ab57311.sharepoint.com/sites/test/SiteAssets/jquery-1.11.3.min.js"></script>

<script>
//https://tjendarta.wordpress.com/2014/02/20/create-retrieve-update-and-delete-sharepoint-list-item-using-rest-api-and-jquery/
//http://www.codeproject.com/Articles/990131/CRUD-operation-to-list-using-SharePoint-Rest-API

var v1, v2, v3, v4, v5, itemid;

$(document).ready(function(){

BindListitems();

$('#input2').change(function () {
 GetListitems();
    });

});
var SiteURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('test')/items";

function GetListitems()
{
var ddlid= $('#input2').val();
var url1 =SiteURL +"?$filter=ID eq " + ddlid;
    $.ajax({
        url: url1,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {

                $('#txtname').val(data.d.results[0].Name);

            }
            else {
                failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            failure(data);
        }
    });
}

function BindListitems()
{
$.ajax({

url:  SiteURL,

        method: "GET",

        headers: { "Accept": "application/json; odata=verbose" },

        success: function (data) {

            var lnt = data.d.results.length;

             for(var i=0; i<lnt; i++ ){

              var title = data.d.results[i].ID;
                 
$('#input2').append("<option value=" + title  + ">" + title  + "</option>");
         

}

        },

        error: function (data) {

           console.log(data.responseJSON.error);

        }

});
}

function CreateNew() {
    var listName = "test";
    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, function () {
        alert("New Item has been created successfully.");
 }, function () {
     alert("Ooops, an error occured. Please try again.");
 });
}

function CreateListItemWithDetails(listName, webUrl, success, failure)
{
var value = $("#txtname").val();
 var itemType = GetItemTypeForListName("test");
    var item = {
        "__metadata": { "type": itemType },
        "Title": "New Title Item added","Name":value
    };

    $.ajax({
        url: SiteURL,
        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);
        }
    });

}

function Update() {
    var listName = "test";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = $('#input2').val(); // Update Item Id here
    var title = $("#txtname").val();
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}
function updateListItem(itemId, listName, siteUrl, title, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Name": 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);
    });
}
function Delete() {
    var listName = "test";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId =$('#input2').val(); // Update Item ID here
    deleteListItem(itemId, listName, url, function () {
        alert("Item deleted successfully");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

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);
   });
}
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);
        }
    });
}
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}


</script>

<table>
<tr><td></td><td>Name</td><td><input type="text" id="txtname"/></td></tr>
<tr><td><input type="submit" value="Save" id="btnsubmit" onclick="CreateNew()" /></td>
<td><input type="submit" value="Update" id="btnUpdate" onclick="Update()" /></td>
<td><input type="submit" value="Delete" id="btnUpdate" onclick="Delete()" /></td>
</tr>
<tr><td></td><td>ID</td><td><select id="input2" style="width:30%"><option>Any</option></select></td></tr>

</table>

No comments:

Post a Comment