I'm trying to update a SharePoint list using Javascript and I found this code.
It's working sometimes but mostly giving me this error
"Request failed. Unexpected response from server.null"
Here is the code i'm using.
function Myfunc()
{
ExecuteOrDelayUntilScriptLoaded(updateListItem, "sp.js");
}
function updateListItem()
{
GetMail();
}
mail = [];
PlainMail =[];
function GetMail() {
$.ajax({
url: "https://MyURL/_api/web/Lists/getbytitle('Notifications')/items?
$select=ServicesId,Author/Id,Author/Name&$expand=Author/Id&$top=50000",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
window.field =
document.getElementById("ctl00_ctl49_g_fd8fcb6f_98bf_4dbf_a73e_1ea566ba0d64_ff61_ctl00_Lookup").value;
$.each(data.d.results, function(index, item){
fullname = item.Author.Name;
window.mailadd = fullname.replace("i:0#.f|membership|","");
var id = item.Author.Id;
var mailid = id + ';#' + window.mailadd;
Array.prototype.contains = function(elem) {
for (var i in this) {
if (this[i] == elem) return true;
}
return false;
}
var arr = item.ServicesId.results;
if (arr.contains(window.field)){
PlainMail.push(window.mailadd)
mail.push(mailid)
}
});
;
mail = mail.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
})
FindMailGroup()
},
error: function(error){
alert(JSON.stringify(error));
}
});
}
function FindMailGroup() {
$.ajax({
url: "https://MyURL_api/web/Lists/getbytitle('MailGroups')/items?
$select=Service/Title,ServiceId,ID&$expand=Service/Title",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
/* For each item in the list build the HTML code*/
$.each(data.d.results, function(index, item){
if (window.field== item.ServiceId) {
window.rowId = item.ID;
window.notificationtext = item.Service.Title
}
});
;
updateList();
},
error: function(error){
alert(JSON.stringify(error));
}
});
}
var siteUrl = 'https://MyURL/';
function updateList (){
var newmail = (mail.join(";#"));
var NewPlainMail = (PlainMail.join(";"));
console.log(window.rowId);
console.log(window.PlainMail);
console.log(NewPlainMail);
var clientContext = new SP.ClientContext(siteUrl);
clientContext.load(clientContext.get_web())
var oList = clientContext.get_web().get_lists().getByTitle('MailGroups');
this.oListItem = oList.getItemById(window.rowId);
oListItem.set_item('ServicePlainText','');
oListItem.set_item('PlainMail','');
oListItem.set_item('ServicePlainText',window.notificationtext);
oListItem.set_item('PlainMail',NewPlainMail);
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this,
this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log('Item updated!');
}
function onQueryFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' +
args.get_stackTrace());
}