0

I am using JSOM and would like to retrieve the id of the newly inserted item. I've tried a few things and nothing has worked.

Any help you can provide would be much appreciated.

var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Travel Request Memos');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    var oListItem = oList.addItem(itemCreateInfo);

        oListItem.set_item('Title', 'Title field');
        oListItem.set_item('From', 'from field');
        oListItem.set_item('Subj', 'subject field');
        oListItem.set_item('To', 'to field');
        oListItem.set_item('Guidance1', guidance1);
        oListItem.set_item('Guidance2', guidance2);
        oListItem.set_item('Guidance3', guidance3);
        oListItem.set_item('Guidance4', guidance4);
        oListItem.set_item('Guidance5', guidance5);     

        oListItem.update();

    clientContext.load(oListItem);
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onAddSucceeded),
    Function.createDelegate(this, this.onAddFailed)
    );
    //alert(oListItem.get_Id());   <-- caused an error
}

function onAddSucceeded(sender, args) {
    $("#divResult").html("Item successfully added!");
}
function onAddFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
}

  • oListItem.get_Id(); will return the id of the newly created item, the problem is the variable oListItem is not accessible in the success function. Just declare the variable as global and it will work. – Ankit Katiyar Apr 8 at 4:06
0

Refer below code. This works perfectly for me:

var oListItem;  //Declared this as a global variable So that it will be accessible in success function
function AddNewItem(){
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Travel Request Memos');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', 'Title field');     
    oListItem.update();

    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onAddSucceeded),Function.createDelegate(this, this.onAddFailed));
}

function onAddSucceeded(sender, args) {
    var newItemId = oListItem.get_id();  //get Id of newly create item
    alert(newItemId);

}
function onAddFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

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.