Update list in a modern site, getting formDigestValue
console.clear();
var dataToManage = {};
function getItemTypeForListName(listTitle, returnfct){
var xhr = new XMLHttpRequest();
var url = _spPageContextInfo.webAbsoluteUrl;
if (url === "undefined") {
console.log("_spPageContextInfo.webAbsoluteUrl undefined");
url = "http://siteUrl";
}
xhr.open('GET', url + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName");
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.onload = function () {
if (xhr.status === 200) {
var kk = JSON.parse(xhr.responseText);
console.dir(kk.d.ListItemEntityTypeFullName);
var returnValue = {};
returnValue.ListItemEntityTypeFullName = kk.d.ListItemEntityTypeFullName;
if(returnfct != null)
returnfct(returnValue);
}
else {
console.dir(xhr);
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}
//get FormDigestValue to do POST requests
function GetDisgestValue(returnFct){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.setRequestHeader("content-type", "application/json; odata=verbose");
xhr.onload = function (data) {
if (xhr.status === 200) {
console.log("success");
var d = JSON.parse(xhr.responseText);
console.dir(d.d.GetContextWebInformation.FormDigestValue);
dataToManage.FormDigestValue = d.d.GetContextWebInformation.FormDigestValue;
returnFct(d.d.GetContextWebInformation.FormDigestValue);
}
else {
console.log("error");
console.log(xhr.status);
console.dir(xhr);
console.dir(xhr.responseText);
}
};
xhr.send();
}
function UpdateListItem(){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle" +
"('" + dataToManage.listName + "')/items("+dataToManage.itemId+")";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.setRequestHeader("X-RequestDigest", dataToManage.FormDigestValue );
xhr.setRequestHeader("content-type", "application/json; odata=verbose");
xhr.setRequestHeader("X-HTTP-Method", "MERGE");
xhr.setRequestHeader("If-Match", "*");
xhr.onload = function () {
if (xhr.status === 204) {
console.log("success");
}
else {
console.log("error");
console.log(xhr.status);
console.dir(xhr);
console.dir(xhr.responseText);
}
};
var str = JSON.stringify(dataToManage.item);
xhr.send(str);
}
function withDigestValue(formDigestValue){
console.log("formDigestValue : " + formDigestValue);
}
function getListDatas(data){
console.log(data.ListItemEntityTypeFullName);
dataToManage.listName = "aTest";//list title to update
dataToManage.itemId = 1;//id of the item to update
dataToManage.item = {
"__metadata": { "type": data.ListItemEntityTypeFullName },
"Title": "new title"//new fields values
};
GetDisgestValue(UpdateListItem);
}
getItemTypeForListName("atest", getListDatas);