Friday, May 17, 2013

SharePoint 2013 - Getting UserName from Person Column in List using JSOM

Here is the code to retrieve person data and convert to string. I have created OrgChart List with Name Column and it's type is Person or Group.

function retrieveListItems()
        {
            clientContext = new SP.ClientContext.get_current();
            //oWeb = clientContext.get_web();
            //oLists = oWeb.get_lists();
            //clientContext.load(oLists, 'Include(Title, Id)');
            //oList = oLists.getByTitle("OrgChart");
            oList = clientContext.get_web().get_lists().getByTitle('OrgChart');
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(
                '' +
                '1
' +                '25
'            );
            oListItems = oList.getItems(camlQuery);
            clientContext.load(oListItems);
            clientContext.executeQueryAsync(
                Function.createDelegate(this,this.onListSuceeded),
                Function.createDelegate(this, this.onListFailed)
                );
        }


function onListSuceeded(sender, args)
        {
            alert("onListSuceeded");
            var EnumerateListItems = oListItems.getEnumerator();
            while (EnumerateListItems.moveNext())
            {
                var oListItem = EnumerateListItems.get_current();
                var assignedToVal = oListItem.get_item('Name');
                var userName = "";
                if (assignedToVal != null)
                    userName = assignedToVal.get_lookupValue();
                alert(userName);
            }
        }


Thursday, April 25, 2013

SharePoint 2013 - External Content Types (BCS) - Part 2

This article will explain you how to use existing external content types.

Step 1 : Go to Central Admin and click on BDC service under Manage Service Application.
Step 2 : Select existing service and click on Set Object Permission

Step 3 : Add any existing user and set permission as below and click ok.

Step 4 : Go to any of existing web application.
Step 5 : Go to Site Content, click on Add an App and select External List.

Step 6 : Provide Name and External Content Type as per screenshot.

Step 7 : Do IISRESET and Navigate to that External List and you will see external data.



Make Sure MACHINENAME\IUSR has enough permision otherwise you will get "Message from External System : 'Login failed for user 'NT AUTHORITY\IUSR'.'." error.




Thursday, April 18, 2013

SharePoint 2013 - External Content Types (BCS) - Part 1

This articles will explain you how to configure external content types.

Step 1 : Open any site using SPD(SharePoint Designer)
Step 2 : Click on External Content Types link from left navigation
Step 3 : Click in External Content Type from menu button
Step 4 : Provide Name, Display Name, Namespace etc as per below screenshot.

Step 5: Click on External System Link
Step 6: Click on Add Connection and select Data Source Type as SQL Server.
Step 7 : Provide Database Server Name, Database Name and select "Connect with User's Identity".

Step 8 : Select any Table and right click on it and select  "Create All Operations". Finish the wizards.

Step 9 : Steps to create external content type "BCSDemo" are completed.







Monday, April 1, 2013

SharePoint 2013 - SharePoint Hosted App For Reading All the List From the Host Web Using Cross-Domain Calls

1. Create any sample project using SharePoint App Template
2. Go to Manifest.xml file and give Read permission for List
3. Edit App.js file and replace with given value



var web;
var hostweburl;
var appweburl;

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { sharePointReady(); });
});

function sharePointReady() {
    hostweburl =
         decodeURIComponent(
             getQueryStringParameter('SPHostUrl')
     );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter('SPAppWebUrl')
     );

    var scriptbase = hostweburl + '/_layouts/15/';

    $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
                function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', printAllListNamesFromHostWeb); }
            );
        }
    );
}

function getQueryStringParameter(param) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i <  params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == param) {
            return singleParam[1];
        }
    }
}

function printAllListNamesFromHostWeb() {
    var context;
    var factory;
    var appContextSite;
    var collList;

    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);

    this.web = appContextSite.get_web();
    collList = this.web.get_lists();
    context.load(collList);

    context.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );

    function successHandler() {
        var listInfo = '';
        var listEnumerator = collList.getEnumerator();

        while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();
            listInfo += '< li>' + oList.get_title() + '< /li>';
        }

        document.getElementById("message").innerHTML = 'Lists found:< ul>' + listInfo + '< /ul>';
    }

    function errorHandler(sender, args) {
        document.getElementById("message").innerText =
            "Could not complete cross-domain call: " + args.get_message();
    }
}

Tuesday, March 19, 2013

SharePoint 2013 - How to create SharePoint Hosted App with App Part


Step 1: Create a new SharePoint-hosted app
In this Step, you will create a new SharePoint-hosted app and make a small number of changes to the code provided.

1.       Launch Visual Studio 2012 and create a new SharePoint-hosted App project and name it SharePoint App Part Demo
2.       In the New App for SharePoint dialog, set the name of the app to SharePointAppPartDemo
3.       Set the debugging site to https://URL/
4.       Host your app for SharePoint as SharePoint-hosted
5.       Click Finish to create the project
Step 2: Add Code for App Part Functionality
In this Step, you will add code to engage the app part functionalities of SharePoint
1.       Double-click the Default.aspx file in the Pages folder and add the following code after the < p>< /p> tag currently inside the < div>< /div> tag
        < p>
            I am the full screen SharePoint app.
        < /p>
2.       Add a new page to the SharePoint App Part Demo project by right clicking on Pages folder and selecting Add New Item
3.       Navigate to Office/SharePoint items and select the Page item and name it AppPart.aspx
4.       Open AppPart.aspx in the editor and replace all the code with the following
< %@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" language="C#" %>
< %@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
< %@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
< %@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
< WebPartPages:AllowFraming ID="AllowFraming" runat="server" />
< !DOCTYPE html>

< html xmlns="http://www.w3.org/1999/xhtml">
< head id="Head1" runat="server">
    < title>Demo App Part< /title>
    < !-- Add your CSS styles to the following file -->
    < link rel="Stylesheet" type="text/css" href="../Content/App.css" />

< /head>
< body>
    < div>I am the Demo App Part.< /div>
< /body>
< /html>  

5.       Add a new item to the SharePoint App Part Demo project by right clicking on SharePoint App Part Demo and selecting Add New Item
6.       Navigate to Office/SharePoint items and select the Client Web Part (Host Web) item and name it Demo App Part, click Add.
7.       In the Specify the client web part page dialog, click the Select or enter a URL for an existing web page radio button, select the AppPart.aspx page and click Finish.
Step 3: Deploy and Test the SharePoint App
  1. Deploy .app file to catalog site.
  2. Edit any page and add that app part to that page



Friday, February 22, 2013

SharePoint 2013 - How to get HostWeb Info from App

First create SharePoint Hosted App using Visual Studio 2012 and add below given html control in default.aspx page

< div>
        < p id="message1">
            < !-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        < /p>
    < /div>
    < div>
        < p id="percentHTML">
            < !-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing..................
        < /p>
    < /div>
    < p id="hostWebURL">< /p>
    < p id="appWebURL">< /p>

    < div id="message">
    < /div>
    < p id="currentWebText">< /p>
    < ul id="listTree">
    < /ul>

    < div id="addItemPanel" style='display: none'>
        Item Title:
        < input type="text" name="itemTitle" title="Item Title" id="itemTitle" />
        < a href="javascript:createListItem()">Create List Item< /a>
    < /div>


Replace App.js file as given below

var context;
var web;
var hostWeb;
var user;

var hostweburl;
var appweburl;
var appContextSite;
var list;
var collList;
var appContextSite;

function getUrl() {
    hostweburl = getQueryStringParameter("SPHostUrl");
    appweburl = getQueryStringParameter("SPAppWebUrl");
    hostweburl = decodeURIComponent(hostweburl);
    appweburl = decodeURIComponent(appweburl);
    $("#hostWebURL").text("Host Web URL: " + hostweburl);
    $("#appWebURL").text("App Web URL: " + appweburl);
}

function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    context = SP.ClientContext.get_current();
    web = context.get_web();

    //getUserName();
    getUrl();
    //getHostweb();
    retrieveWebSiteProperties();

});

function getHostweb() {
    var appContextSite = new SP.AppContextSite(
        context,
        hostweburl
    );
    hostWeb = appContextSite.get_web();
    context.load(hostWeb);
    context.executeQueryAsync(onSuccess, onFail);

}
function onSuccess() {
    $('#hostWebInfo').text("Host web title through api " + hostWeb.get_title());
}

// This function is executed if the above call fails
function onFail(sender, args) {
    alert(args.get_message());
}


// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    user = web.get_currentUser();
    context.load(web, 'Title');
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above OM call is successful
// It replaces the contents of the 'helloString' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
    $('#currentWebText').text("Current Web Context: " + web.get_title());

}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}


function retrieveWebSiteProperties() {

    appContextSite = new SP.AppContextSite(
        context,
        hostweburl
    );
    hostWeb = appContextSite.get_web();
    context.load(hostWeb, 'Title', 'Created');

    collList = hostWeb.get_lists();
    context.load(collList, 'Include(Title, Id)');

    context.executeQueryAsync(
        Function.createDelegate(this, onQuerySucceeded),
        Function.createDelegate(this, onQueryFailed)
    );
}

function onQuerySucceeded(sender, args) {
    var message = 'Title: ' + hostWeb.get_title() +
        ' Created: ' + hostWeb.get_created();

    document.getElementById("message").innerText = message;

    //display lists
    var listEnumerator = collList.getEnumerator();
    var listTree = document.getElementById("listTree");
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        var listTitle = oList.get_title();
        var li = document.createElement("li");
        li.id = listTitle;
        li.appendChild(document.createTextNode(listTitle));
        listTree.appendChild(li);
        if (listTitle == "CustomList1") {
            getListItems();
        }
    }
}

function getListItems() {
    //alert('getting list items');
    //var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');
    var oList = appContextSite.get_web().get_lists().getByTitle('CustomList1');
    var camlQuery = new SP.CamlQuery();
 

camlQuery.set_viewXml(
        '< View>< Query>< Where>< Geq>< FieldRef Name=\'ID\'/>' +
        '< Value Type=\'Number\'>1< /Value>< /Geq>< /Where>< /Query>' +
        '< RowLimit>25< /RowLimit>< /View>'
    );
    this.collListItem = oList.getItems(camlQuery);

    context.load(collListItem);
    context.executeQueryAsync(
        Function.createDelegate(this, onItemsGetQuerySucceeded),
        Function.createDelegate(this, onQueryFailed)
    );

}

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


function createListItem() {

    //var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');
    var oList = appContextSite.get_web().get_lists().getByTitle('CustomList1');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', document.getElementById("itemTitle").value);
    oListItem.update();

    context.load(oListItem);
    context.executeQueryAsync(
        Function.createDelegate(this, this.onItemCreateQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}


function onItemsGetQuerySucceeded() {
    var listItemEnumerator = collListItem.getEnumerator();

    var cl = document.getElementById("CustomList1");
    while (cl.childNodes.length > 0) {
        cl.removeChild(cl.childNodes[0]);

    }
    cl.textContent = cl.id;
    var ul = document.createElement("ul");;
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var li = document.createElement("li");
        li.appendChild(document.createTextNode("Title:" + oListItem.get_item('Title') + " Title: " + oListItem.get_item('Title')));
        ul.appendChild(li);
    }
    cl.appendChild(ul);
    var div = document.createElement("div");
    div.innerHTML = document.getElementById("addItemPanel").innerHTML;
    cl.appendChild(div);
}

function onItemCreateQuerySucceeded() {
    //alert('Item created: ' + oListItem.get_id());
    getListItems();
}


Saturday, February 16, 2013

SharePoint 2013 - How to get AppWeb Info from App

First create SharePoint Hosted App using Visual Studio 2012 and add below given html control in default.aspx page

 < div>
        < p id="message1">
            initializing...
        < /p>
    < /div>
    < div>
        < p id="percentHTML">
            initializing..................
        < /p>
    < /div>
    < p id="hostWebURL">< /p>
    < p id="appWebURL">< /p>

    < div id="message">
    < /div>
    < p id="currentWebText">< /p>
    < ul id="listTree">
    < /ul>

    < div id="addItemPanel" style='display: none'>
        Item Title:
        < input type="text" name="itemTitle" title="Item Title" id="itemTitle" />
        < a href="javascript:createListItem()">Create List Item< /a>
    < /div>


Replace App.js as below


'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var oWebsite;
var collList;
var clientContext;




// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
    //drawTable();
    retrieveWebSiteProperties();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message1').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

function retrieveWebSiteProperties() {
    clientContext = new SP.ClientContext.get_current();
         
    oWebsite = clientContext.get_web();
    clientContext.load(oWebsite, 'Title', 'Created');
         

    collList = oWebsite.get_lists();
    clientContext.load(collList, 'Include(Title, Id)');

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

function onQuerySucceeded(sender, args) {
    var message = 'Title: ' + oWebsite.get_title() +
        ' Created: ' + oWebsite.get_created();

    document.getElementById("message").innerText = message;

    //display lists
    var listEnumerator = collList.getEnumerator();
    var listTree = document.getElementById("listTree");
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        var listTitle = oList.get_title();
        var li = document.createElement("li");
        li.id = listTitle;
        li.appendChild(document.createTextNode(listTitle));
        listTree.appendChild(li);
        if (listTitle == "CustomList1") {
            getListItems();
        }
    }
}

function getListItems() {
    //alert('getting list items');
    var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');

    var camlQuery = new SP.CamlQuery();
   camlQuery.set_viewXml(
        '< View>< Query>< Where>< Geq>< FieldRef Name=\'ID\'/>' +
        '< Value Type=\'Number\'>1< /Value>< /Geq>< /Where>< /Query>' +
        '< RowLimit>25< /RowLimit>< /View>'
    );
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onItemsGetQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );

}

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


function createListItem() {

    var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', document.getElementById("itemTitle").value);
    oListItem.update();

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


function onItemsGetQuerySucceeded() {
    var listItemEnumerator = collListItem.getEnumerator();

    var cl = document.getElementById("CustomList1");
    while (cl.childNodes.length > 0) {
        cl.removeChild(cl.childNodes[0]);

    }
    cl.textContent = cl.id;
    var ul = document.createElement("ul");;
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var li = document.createElement("li");
        li.appendChild(document.createTextNode("Title:" + oListItem.get_item('Title') + " Title: " + oListItem.get_item('Title')));
        ul.appendChild(li);
    }
    cl.appendChild(ul);
    var div = document.createElement("div");
    div.innerHTML = document.getElementById("addItemPanel").innerHTML;
    cl.appendChild(div);
}

function onItemCreateQuerySucceeded() {
    //alert('Item created: ' + oListItem.get_id());
    getListItems();
}


Friday, January 25, 2013

SharePoint 2013 - Retrieving List/ List Items using REST Service

Sample code to retrieve Lists and List Items using REST service in SharePoint 2013

 < %@ Page Language="C#" %>

< !DOCTYPE html>

< script runat="server">

< /script>

< html xmlns="http://www.w3.org/1999/xhtml">
< head id="Head1" runat="server">
    < title>Basic Rest Client< /title>
< script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js">< /script>
< /head>
< body>

< script type="text/javascript">
    $(document).ready(function () {

        $.ajax({
            url: "http://goazrapp19.cloudapp.net/_api/web/lists",
            type: "GET",
            headers: {
                "ACCEPT": "application/json;odata=verbose"
            },
            success: function (data) {
                //document.getElementById("message").innerText = JSON.stringify(data, null, "\t");
                var results = data["d"]["results"];
                var listTree = document.getElementById("listTree");

                for (var i = 0, length = results.length; i <  length; i++) {
                    var result = results[i];
                    console.log(result["Title"] + " " + result["ItemCount"]);
                    var listTitle = result["Title"];
                    var li = document.createElement("li");
                    li.id = listTitle;
                    li.appendChild(document.createTextNode(listTitle));
                    listTree.appendChild(li);
                    getListItems(result["__metadata"]["uri"], li);
                }
            },
            failure: function (data) {
                console.log("got an error");
            }
        });

        function getListItems(listURL, liList) {
            $.ajax({
                url: listURL + "/Items",
                type: "GET",
                headers: {
                    "ACCEPT": "application/json;odata=verbose"
                },
                success: function (data) {
                    var results = data["d"]["results"];
                    console.log(JSON.stringify(results));
                    var ul = document.createElement('ul');

                    for (var i = 0, length = results.length; i <  length; i++) {
                        var result = results[i];
                        // console.log(result["Title"]);
                        var li = document.createElement("li");
                        li.appendChild(document.createTextNode(result["Title"]));
                        ul.appendChild(li);

                    }
                    liList.appendChild(ul);
                },
                failure: function (data) {
                    console.log("got an error getting items");
                }
            });
        }
    });
< /script>    < form id="form1" runat="server">
   
         < div id="message">
            < /div>
    < ul id="listTree">
    < /ul>
    < /form>
< /body>
< /html>

Wednesday, January 23, 2013

SharePoint 2013 - Retrieving ListItem using JSOM (Javascript Object Model)

Here is the same code to fetch list/list item and create new list item using JSOM.

< %@ Page Language="C#" %>

< !DOCTYPE html>

< script runat="server">

< /script>

< html xmlns="http://www.w3.org/1999/xhtml">
< head id="Head1" runat="server">
    < title>Basic Javascript client< /title>

< /head>
< body>
< script
    src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"
    type="text/javascript">
< /script>
< script
    type="text/javascript"
    src="/_layouts/15/sp.runtime.js">
< /script>
< script
    type="text/javascript"
    src="/_layouts/15/sp.js">
< /script>
    < script type="text/javascript">



        var collList;
        var clientContext;

        retrieveWebSiteProperties();

        function retrieveWebSiteProperties() {
            clientContext = new SP.ClientContext.get_current();

            this.oWebsite = clientContext.get_web();
            clientContext.load(this.oWebsite, 'Title', 'Created');


            collList = oWebsite.get_lists();
            clientContext.load(collList, 'Include(Title, Id)');

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

        function onQuerySucceeded(sender, args) {
            var message = 'Title: ' + this.oWebsite.get_title() +
                ' Created: ' + this.oWebsite.get_created();

            document.getElementById("message").innerText = message;

            //display lists
            var listEnumerator = collList.getEnumerator();
            var listTree = document.getElementById("listTree");
            while (listEnumerator.moveNext()) {
                var oList = listEnumerator.get_current();
                var listTitle = oList.get_title();
                var li = document.createElement("li");
                li.id = listTitle;
                li.appendChild(document.createTextNode(listTitle));
                listTree.appendChild(li);
                if (listTitle == "CustomList1") {
                    getListItems();
                }
            }
        }

        function getListItems() {
            //alert('getting list items');
            var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');

            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(
                '< View>< Query>< Where>< Geq>< FieldRef Name=\'ID\'/>' +
                '< Value Type=\'Number\'>1< /Value>< /Geq>< /Where>< /Query>' +
                '< RowLimit>25< /RowLimit>< /View>'
            );
            this.collListItem = oList.getItems(camlQuery);

            clientContext.load(collListItem);
            clientContext.executeQueryAsync(
                Function.createDelegate(this, this.onItemsGetQuerySucceeded),
                Function.createDelegate(this, this.onQueryFailed)
            );

        }

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


        function createListItem() {

            var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');

            var itemCreateInfo = new SP.ListItemCreationInformation();
            this.oListItem = oList.addItem(itemCreateInfo);
            oListItem.set_item('Title', document.getElementById("itemTitle").value);
            oListItem.update();

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


        function onItemsGetQuerySucceeded() {
            var listItemEnumerator = collListItem.getEnumerator();

            var cl = document.getElementById("CustomList1");
            while (cl.childNodes.length > 0) {
                cl.removeChild(cl.childNodes[0]);

            }
            cl.textContent = cl.id;
            var ul = document.createElement("ul");;
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                var li = document.createElement("li");
                li.appendChild(document.createTextNode("Title:" + oListItem.get_item('Title') + " Name: " + oListItem.get_item('Name')));
                ul.appendChild(li);
            }
            cl.appendChild(ul);
            var div = document.createElement("div");
            div.innerHTML = document.getElementById("addItemPanel").innerHTML;
            cl.appendChild(div);
        }

        function onItemCreateQuerySucceeded() {
            //alert('Item created: ' + oListItem.get_id());
            getListItems();
        }

< /script>

    < form id="form1" runat="server">
    < div id="message">
    < /div>
    < ul id="listTree">
    < /ul>
 
    < div id="addItemPanel" style='display:none'>    
    Item Title: < input type="text" name="itemTitle" title="Item Title" id="itemTitle"/>
    < a href="javascript:createListItem()">Create List Item< /a>
    < /div>
    < /form>
< /body>
< /html>