1

I'm currently using JSOM to insert new items to list.

   var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle("request");
    var camlQuery = new SP.CamlQuery();
    var oListItemCreationInformation = new SP.ListItemCreationInformation();
    var oListItem = oList.addItem(oListItemCreationInformation);

    oListItem.set_item('formType', ftype);
oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(onsuccess(), onfailed);

}
function onsuccess() {
    alert("Success");
    console.log( oListItem.get_id());
    
}

As I expected it will return the new item ID, but it only return -1.

What can I do to get the correct ID in order to help adding upload file to list function to my page?

0

Try defining define oListItem as a global variable like below:

var oListItem;

function insertListItem() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle("request");
    var camlQuery = new SP.CamlQuery();
    var oListItemCreationInformation = new SP.ListItemCreationInformation();
    oListItem = oList.addItem(oListItemCreationInformation);

    oListItem.set_item('formType', ftype);
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(onsuccess, onfailed);
}
function onsuccess(sender, args) {
    alert("Success");
    console.log(oListItem.get_id());
}

OR

Try using an inline function instead of a named function for the success handler. That way you will not need to add a global variable.

clientContext.executeQueryAsync(
    function (sender, args) {
        var itemId = oListItem.get_id();
        console.log(itemId);
    },
    function (sender, args) {
        alert("failed");
    }
);

Source: Get ID after inserting Item into SharePoint 2013 Host Web List

1
  • 1
    thank you! I've try and that's work for me!
    – bensonwong
    Aug 11 '21 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.