Adding an Item to a SharePoint List using JavaScript

I found out that adding an item to a list using the Sharepoint client OM  in SharePoint 2010 is not as simple as it seems to be. There are plenty of examples on demos using the Sharepoint client OM in the code behind. But I couldn’t get my hands on how to do this using JavaScript. And the documentation on SP.js isn’t available yet. So how did i do it?

The Preparation

1. Create a custom list named Cars.

2. Create a new Empty SharePoint project.

3. Add a mapped Layouts folder

4. Add a page called AddCarPage.aspx

5. Create JavaScript method called AddCar.

6. Add an input of type button and set it’s onclick to AddCar(). another input of type text and name it as txtCar.

The PlaceHolderMain of the ASPX page should now look something like this :

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<input type="text" id="txtCar" />
<input type="button" id="btnAddCar" onclick="AddCar();" value="Add Car" />
<label id ="lbl" runat="server"/>
</asp:Content>

The SharePoint

We need to include the SharePoint ECMAScript library in the aspx page.The main file is SP.js . Information about all the ECMAScript Library can be found here. Including the SP.js can be done using the SharePoint:ScriptLink tag.

<Sharepoint:ScriptLink name="SP.js" runat="server" OnDemand="true" localizable="false" />

We will write our code in the AddCar JavaScript method.

function AddCar() {
//Retrieve the txtCar and check if it has some text.
var txtCar = document.getElementById("txtCar");
if (txtCar.value == "") {
alert("please enter a car");
return;
}
//Retrieve the clientContext
var clientContext = SP.ClientContext.get_current();
//Retrieve the current website
var webSite = clientContext.get_web();
//Retrieve the lists
var lists = webSite.get_lists();
//Get the Cars List
var carsList = lists.getByTitle("Cars");
//Create new IteamCreationInformation
var itemCreationInfo = new SP.ListItemCreationInformation();
//the addItem takes the itemCreationInformation object
//and returns the listItem
var listItem = carsList.addItem(itemCreationInfo);
//Set the title of the list Item
//to the value in the txtCar
listItem.set_item("Title", txtCar.value);
//Call Update the listItem
listItem.update();
//Finally execute the operation
//pass to it a 2 callBack methods OnSucceed and OnFailure
clientContext.executeQueryAsync(
Function.createDelegate(this,this.Succeeded)
,Function.createDelegate(this,this.Failed));
}

Finally add the 2 CallBack method

function Succeeded() {
alert("Succeeded");
}
function Failed(sender,args) {
alert("fail");
}

Advertisements

13 Responses to Adding an Item to a SharePoint List using JavaScript

  1. Pingback: Using the Sharepoint 2010 Dialog « Islam Shaalan's Blog

  2. Elizabeth says:

    How can we localize the title of a sharepoint 2010 dialog window?

  3. bronyx says:

    Hi.
    I have used the above code; but the issue i have is. I have a list saved in the root site!. i then have several subsites..
    When i click the sae button, i want it to save to the list which is based in the root site ; but i get an error saying “the list does not exsist within this site’.
    This error is caused because the code is searching the ‘current site’ for the list… but the list lives in the root site.
    Can you please show/tell me the code to save a item to a list from a subite to a list based in the root site please.

    • ishaalan says:

      Can you show me your code?

      • bronyx says:

        Sorry ishaalan, i beleive i should have placed the code in this box. The code is below.

        The code works fine on the root site, because that is where the List ‘Favourites’ Lives…
        But when on a subsite, the code cant find the ‘Favourites’ List….
        Is ther a property which instead of looking at the current site your on, looks at the root/parent site….?

        function addToList(){

        // Obtain current URL
        var url = window.location;
        var pageTitle = document.title;

        try {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();

        // Get specified list
        var list = web.get_lists().getByTitle(‘Favourites’);

        // Create a new empty list
        var listItemCreationInfo = new SP.ListItemCreationInformation();
        var newItem = list.addItem(listItemCreationInfo);

        // Populate rows with specified data
        newItem.set_item(‘Title’, pageTitle.slice(7).toString());
        newItem.set_item(‘URL’, url.toString()); // ensuring url is captured in correct format
        //newItem.set_item(‘Created By’, “”);
        //newItem.set_item(‘Modified By’, “”);

        newItem.update();

        // Check if list has successfully been updated
        // and handle response
        context.executeQueryAsync(nextStep, handleError);

        }
        catch (e) {
        alert(‘error:’ + e.Message);
        }
        }

        function nextStep()
        {
        alert(‘Added to Favourites’);
        }

        function handleError(sender, args)
        {
        alert(‘Sorry we encountered an error processing your request.\n’ + args.get_message());
        }

        $(“a.s4-breadcrumbRootNode”).clone().appendTo(‘div.wss-BreadCrumb’);
        $(“a.s4-breadcrumbNode”).clone().appendTo(‘div.wss-BreadCrumb’);
        $(“a.s4-breadcrumbCurrentNode”).clone().appendTo(‘div.wss-BreadCrumb’);
        $(“>”).insertAfter(‘div.wss-BreadCrumb a.s4-breadcrumbRootNode’);
        $(“>”).insertAfter(‘div.wss-BreadCrumb a.s4-breadcrumbNode’);
        $(“span.s4-breadcrumbCurrentNode”).clone().appendTo(‘div.wss-BreadCrumb’);

      • bronyx says:

        Would it be ok, if you could please delte the code above, as it aleady appears below..
        thanks

  4. bronyx says:

    Thanks for your rely. I beleive its something to do with the Sp.ClientContext.get_currnet() ;

    Code below

    function addToList(){

    // Obtain current URL
    var url = window.location;
    var pageTitle = document.title;

    try {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();

    // Get specified list
    var list = web.get_lists().getByTitle(MyList);

    // Create a new empty list
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = list.addItem(listItemCreationInfo);

    // Populate rows with specified data
    newItem.set_item(‘Title’, pageTitle());
    newItem.set_item(‘URL’, url.toString()); // ensuring url is captured in correct format
    //newItem.set_item(‘Created By’, “”);
    //newItem.set_item(‘Modified By’, “”);

    newItem.update();

    // Check if list has successfully been updated
    // and handle response
    context.executeQueryAsync(nextStep, handleError);

    }
    catch (e) {
    alert(‘error:’ + e.Message);
    }
    }

    function nextStep()
    {
    alert(‘Added to Favourites’);
    }

    function handleError(sender, args)
    {
    alert(‘Sorry we encountered an error processing your request.\n’ + args.get_message());
    }

  5. Goutham says:

    Hii Ishan

    here is my code. I need to check if the item is already existing before adding it . Please help .

    function initializeScript()
    {

    var clientContext = SP.ClientContext.get_current();
    var webSite = clientContext.get_web();
    var lists = webSite.get_lists();
    var oList= lists.getByTitle(“ReadMore”);

    //Retrieve the url.
    var pathname = location.href;
    var loggedUser = webSite.get_currentUser();

    var itemCreationInfo = new SP.ListItemCreationInformation();
    var listItem = oList.addItem(itemCreationInfo);

    listItem.set_item(“Title”, pathname);
    listItem.set_item(“UserName”, loggedUser);
    listItem.update();

    clientContext.executeQueryAsync(
    Function.createDelegate(this,this.Succeeded)
    ,Function.createDelegate(this,this.Failed));
    }

    function Succeeded() {
    alert(“Succeeded”);
    }
    function Failed(sender,args) {
    alert(“fail”);
    }

  6. Hello, I wish for to subscribe for this weblog to take latest updates,
    thus where can i do it please help.

  7. Excellent beat ! I would like to apprentice while you amend your website, how
    could i subscribe for a blog website? The account aided me
    a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright
    clear idea

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: