0

I created a function to get RequestDigest: async function getRequestDigest() at modern site, then before the ajax code in createItem function, I called getRequestDigest() to set const digest= await getRequestDigest();

However keep getting the error that: Uncaught SyntaxError: Failed to execute 'insertBefore' on 'Node': await is only valid in async functions and the top level bodies of modules

function createItem(id, Title)
{
    var Url= _spPageContextInfo.webAbsoluteUrl+ "/_api/web/lists/getbytitle('"+ ListName +"')/items";
    var itemType = GetItemTypeForListName(ListName);
    var item={
        "__metadata":{"type": itemType},
        "Title": Title,
        "ParentId":id           
    };

    const digest= await getRequestDigest();

    $.ajax({

        url: Url,
        type:"POST",    
        data: JSON.stringify(item),
        async:false,

        headers:{
            "accept": "application/json;odata=verbose",
          "content-Type": "application/json;odata=verbose",
            "X-RequestDigest": digest
        },

        success:function(data){
            console.log("You have successfully created a new item");

        },

        error:function(data){
            console.log("Error occured");
            alert("Error Occured while creating " + Title);
        }
    });
}

async function getRequestDigest() { const response=await fetch(${_spPageContextInfo.webAbsoluteUrl}/_api/contextinfo,{ method:"POST", headers:{ "Accept":"application/json;odata=verbose" } });

const data=await response.json();
return data.d.GetContextWebInformation.FormDigestValue;

}

1
  • Why there are two commas after ParentId:id, , ? Commented Jul 17 at 8:31

1 Answer 1

1

$("#__REQUESTDIGEST").val() this will return undefined in modern SharePoint site. It doesn't render in modern pages. You may need to get request digest in separate call to the api /_api/contextinfo. And then use this digest in your subsequent requests.

$.ajax({
  url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
  type: "POST",
  headers: {
    "Accept": "application/json;odata=verbose"
  },
  success: function (data) {
    var digest = data.d.GetContextWebInformation.FormDigestValue;
    createItem(digest); // Pass it to your POST function
  }
});



function createItem(digest) {
  $.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('YourList')/items",
    type: "POST",
    data: JSON.stringify(item),
    headers: {
      "Accept": "application/json;odata=verbose",
      "Content-Type": "application/json;odata=verbose",
      "X-RequestDigest": digest
    },
    success: function (data) {
      console.log("Item created successfully");
    },
    error: function (err) {
      console.error("Error creating item", err);
    }
  });
}

Note: In modern pages/sites, inline scripts are may not work as expected due to content security policies. You might need to enable scripts injections and all. I would recommend using SPFx web-part or customiser (choose one based on your requirement). in SPFx you can then use PnPJS library or directly make rest calls using SPHttpClient

1
  • I created a function to get RequestDigest: async function getRequestDigest() then before the ajax code in createItem function, I called getRequestDigest() to set const digest= await getRequestDigest(); however keep getting the error that: VM9300:138 Uncaught SyntaxError: Failed to execute 'insertBefore' on 'Node': await is only valid in async functions and the top level bodies of modules -- see updated code above Commented Jul 17 at 21:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.