1

I am currently creating a SharePoint 2013 hosted app on Office 365 and I currently have some JavaScript that inserts item into a host web list.

I wondering if it is possible to get the ID of the item that has just been created in the list using the current JavaScript code:

function Sumbit() {
$('#submitBtn').click(function () {
    var ctx = new SP.ClientContext(appweburl);
    var appCtxSite = new SP.AppContextSite(ctx, hostweburl);

    var web = appCtxSite.get_web();
    var List = web.get_lists().getByTitle('List Title');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    var ListItem = List.addItem(itemCreateInfo);

    ListItem.set_item('Title', $('#title').val());
    ListItem.set_item('Description', $('#Description').val());

    ListItem.update();

    ctx.load(ListItem);

    ctx.executeQueryAsync(
        Function.createDelegate(this, QuerySucceeded),
        Function.createDelegate(this, QueryFailed));
});
}


function QuerySucceeded(sender, args) {
console.log("success");


 }

function QueryFailed(sender, args) {
console.log(args.get_message() + '\n' + args.get_stackTrace());

}

I have tried getting the ID inside of the 'QuerySucceeded' function by using:

ListItem.get_id();

However this was returning '-1' any help with this would be greatly appreciated.

1

May be you should try declaring your ListItem variable globally, what I can see from your code is that it is local to Submit function. Refer below code change.

// Declared globally which can be accessible in other functions as well
var ListItem = null;

function Sumbit() {
    $('#submitBtn').click(function () {
        var ctx = new SP.ClientContext(appweburl);
        var appCtxSite = new SP.AppContextSite(ctx, hostweburl);

        var web = appCtxSite.get_web();
        var List = web.get_lists().getByTitle('List Title');

        var itemCreateInfo = new SP.ListItemCreationInformation();
        ListItem = List.addItem(itemCreateInfo);

        ListItem.set_item('Title', $('#title').val());
        ListItem.set_item('Description', $('#Description').val());

        ListItem.update();

        ctx.load(ListItem);

        ctx.executeQueryAsync(
            Function.createDelegate(this, QuerySucceeded),
            Function.createDelegate(this, QueryFailed));
    });
}


function QuerySucceeded(sender, args) {
    console.log("success");
}

function QueryFailed(sender, args) {
    console.log(args.get_message() + '\n' + args.get_stackTrace());
}
1

I think you can use the function "RefreshLoad()" on the ListItem before using ListItem.get_id(); . Don't forget to use an executequery on your context before re-using it.

  • Do you have an example of this please? – Adam13Hylo Aug 19 '15 at 11:49

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.