4

I need reference code to add an item to a list programmaticaly via javascript object model in SharePoint 2013.. Got many solutions online but not sure what js to include, whether ajax calls are need as given in this msdn article.

Basically the javascript will be put into an application page and every time the page is opened/refreshed a new item with logged in username should get inserted into the list.

Thanks.

7
  • You are referring the right article .You do not need any ajax calls. Refer this Section:msdn.microsoft.com/en-us/library/office/… of the same article.
    – Unnie
    Commented Mar 21, 2014 at 5:07
  • I cannot use the section code mentioned without importing some js files right..? Dont I have to add reference to some js or ajax file?
    – variable
    Commented Mar 21, 2014 at 5:10
  • Yes make sure this code is run after 'SP.js' is loaded. You can call your method to create list item like this SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem);. See this link for more info about this msdn.microsoft.com/en-us/library/office/…
    – Unnie
    Commented Mar 21, 2014 at 5:14
  • what about: ExecuteOrDelayUntilScriptLoaded?
    – variable
    Commented Mar 21, 2014 at 5:17
  • I want a article that has this simple code. Sadly there are none that I found.
    – variable
    Commented Mar 21, 2014 at 5:24

3 Answers 3

6

You can refer this Section to add/update/Delete list items using javascript.

Make sure 'SP.js' is loaded before you call your method to add list item.You can do that as below:

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem);//makes sure sp.js is loaded and then calls createListItem method
    function createListItem() {
        var clientContext = new SP.ClientContext.get_current();//if the page and the list are in same site.If list is in different site then use relative url instead of get_current
        var oList = clientContext.get_web().get_lists().getByTitle('ListName');

        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('Title', 'My New Item!');
        oListItem.set_item('Body', 'Hello World!');
        oListItem.update();

        clientContext.load(oListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded), 
            Function.createDelegate(this, this.onQueryFailed)
        );
    }

    function onQuerySucceeded() {
        alert('Item created: ' + oListItem.get_id());
    }

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

SharePoint CSOM List client object exposes List.AddItem method to create a new list item in the list:

public ListItem AddItem(
    ListItemCreationInformation parameters
)

Since CSOM is asynchronous, two approaches are commonly used when it comes to make CSOM code maintainable:

  • Callbacks
  • Deferred

Callback approach

function AddListItem(listTitle,itemProps,OnItemAdded,OnItemError)
{
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();

    var list = web.get_lists().getByTitle(listTitle);
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);

    for(var propName in itemProps) {
       listItem.set_item(propName, itemProps[propName]) 
    }

    listItem.update();
    context.load(listItem);
    context.executeQueryAsync(
        function() {
          OnItemAdded(listItem);           
        },
        OnItemError
    );
}

Usage

AddListItem('Contacts',contactEntry,
         function(contactItem){
            console.log('Contact ' + contactItem.get_item('Title') + ' has been created successfully');
         },
         function(sender,args){
            console.log('Error occured while creating contact:' + args.get_message());
});

Deferred approach

A deferred - is a pattern that returns an object immediately from an asynchronous call

function AddListItemD(listTitle,itemProps)
{
    var dfd = $.Deferred(function () {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();

        var list = web.get_lists().getByTitle(listTitle);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var listItem = list.addItem(itemCreateInfo);

        for(var propName in itemProps) {
           listItem.set_item(propName, itemProps[propName]) 
        }

        listItem.update();
        context.load(listItem);
        context.executeQueryAsync(
            function () {
               dfd.resolve(listItem);
            },
            function (sender, args) {
               dfd.reject(args.get_message());
            }
        );
    });
    return dfd.promise();    
}

Usage

AddListItemD('Contacts',contactEntry).then(function(contactItem){
    console.log('Contact ' + contactItem.get_item('Title') + ' has been created successfully');
});

Since SP.SOD.executeFunc supports on demand scripts, but SP.SOD.executeOrDelayUntilScriptLoaded does not, I would recommend to use SP.SOD.executeFunc with CSOM in application pages:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
    var clientContext = SP.ClientContext.get_current();

});
2

please see my post here, it will tell you how to add a SP.List item with all available column types by using JSOM

http://pointofint.blogspot.com/2014/03/how-to-set-any-spfield-value-with-jsom.html

1
  • 1
    Add details to your post instead of linking to your own blog. If your blog goes down your answer will not be helpful at all to future readers Commented Mar 21, 2014 at 5:30

Your Answer

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

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