1

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());
 }
3
  • Do you use this code in SharePoint Add-in ? Commented Jun 27, 2017 at 19:10
  • No, it's running from a Content Editor. Commented Jun 27, 2017 at 19:12
  • Sometimes it gives me the error but the list has been updated anyway Commented Jun 27, 2017 at 19:16

2 Answers 2

1

In case you are using this script within SharePoint CEWP, so you should use ExecuteOrDelayUntilScriptLoaded method to delay the function call until the (SP.js) is loaded.

So try to do following:

function Myfunc()
{
    ExecuteOrDelayUntilScriptLoaded(updateListItem, "sp.js");
}

function updateListItem() 
{
    // your code
}

_spBodyOnLoadFunctionNames.push("Myfunc");

For more details check Sharepoint 2013 Request failed unexpected response data from server. null

6
  • I'm using CEWP but the script is only loaded when a save button is clicked in a form. Commented Jun 27, 2017 at 19:42
  • Should it be before all of my code or just the update list part? I have tried both but I still get the error. Commented Jun 27, 2017 at 20:02
  • Please share your full code to can help you faster also to try it in my side Commented Jun 27, 2017 at 20:02
  • Should be there now Commented Jun 27, 2017 at 20:10
  • Okay let me check Commented Jun 27, 2017 at 20:16
0

You need to load the item since its client script. I believe since you aren't loading the item you are receiving that null error. You need to load items using this method ClientContext.load.

4
  • Could you point me in the direction on how this is done? Commented Jun 27, 2017 at 19:23
  • I think if you just add clientContext.load(clientContext.get_web()); after you create the client context it should load everything from the site for you to use. If you want to only load specific lists or items you just change the argument for load(), which takes client objects. Look at that link I posted in the answer for the documentation. Commented Jun 27, 2017 at 19:29
  • I still get the same error Commented Jun 27, 2017 at 19:36
  • Then try the ExecuteOrDelayUntilScriptLoaded method that @M.Qassas recommended. I think the error is definitely happening because something from the site isn't loaded when you try and use it. Good luck. Commented Jun 27, 2017 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.