Adding Multiple value to lookup field via REST

             var itemProperties = {
                ‘__metadata’: { “type”: “SP.Data.QuestionsListItem” },
                ‘AnsChoicesId’: { “results”: [1,3] }  //multi-valued User field value 
            };

            $.ajax({

                url: appweburl + “/_api/web/lists/GetByTitle(‘ListTitleGoesHere’)/items(“+ListItem+”)”,
                type: “MERGE”,
                data: JSON.stringify(itemProperties),
                headers: {
                    “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
                    “accept”: “application/json; odata=verbose”,
                    “If-Match”: “*”,
                    “content-type”: “application/json;odata=verbose”
                }
            }).done(function () {
                console.log(“Done”);
            }).fail(function () {
                console.log(“FaiL”);
            });


In the above code all of the array items will be replaced with the item ID’s specified. 

//code coming soon

Here is what adding Multiple values looks like in JSOM (This example is create a new record, not updating a record)

var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle(‘ListTitleGoesHere’);
            var itemCreateInfo = new SP.ListItemCreationInformation();
            oListItem = oList.addItem(itemCreateInfo);
            oListItem.set_item(‘Title’, ‘HelloThisStuffWorld’);
            var lookupsIds = [1, 2, 3];
            var lookups = [];
            for (var ii in lookupsIds) {
                var lookupValue = new SP.FieldLookupValue();
                lookupValue.set_lookupId(lookupsIds[ii]);
                lookups.push(lookupValue);
            }
            oListItem.set_item(‘AnsChoices’, lookups);
            oListItem.update();
            clientContext.load(oListItem);
            clientContext.executeQueryAsync(
         function () { alert(“Success!”) },
         function () { alert(“Request failed”) }

        );

Create and add data to a file in SharePoint Online using JavaScript

$(document).ready(function () {

    clientContext = SP.ClientContext.get_current();

    $(“#btnPublish”).click(function () {
        getSPItems();
    });

    function getSPItems() {

        var spList = clientContext.get_web().get_lists().getByTitle(‘Team_Members’);

        var camlQuery = new SP.CamlQuery();

        listItems = spList.getItems(camlQuery);

        clientContext.load(listItems);

        clientContext.executeQueryAsync(saveHtmlFile, onFailure);
    }

    function saveHtmlFile() {

        // var fileContent = uiContext.getJSContent();
        var fileContent = “”;
        Enum = listItems.getEnumerator();
        while (Enum.moveNext()) {
            GetTitle = Enum.current.get_fieldValues();
            fileContent += ” <div style=’position:relative;padding-bottom:10px’><img src='” + GetTitle.Image.$1_1 + “‘ alt=’employee Images’ style=’position:absolute’ height=’87’ width=’87’> <ul style=’padding-left:125px;list-style-image:url(../Images/tinyArrow.gif)’><li style=’padding-bottom:5px’><span style=’font-weight:bold’>” + GetTitle.Title + “</span></li><li style=’padding-bottom:5px’><span style=’font-weight:bold’>” + GetTitle.Position + “</span></li><li style=’padding-bottom:5px’><span style=’font-weight:bold’>” + GetTitle.Department1 + “</span></li><li class=’lastInRow’ style=’padding-bottom:5px’>” + GetTitle.Bio + “</li></ul></div>”;

        }

        var jsContent = “(function () {“
                          + “$(‘#divContent’).html(“” + fileContent + “”);”
                          + “})();”;

        var filesLibrary = clientContext.get_web().get_lists().getByTitle(“JSCompile”);
        var fileCreateInfo = new SP.FileCreationInformation();

        fileCreateInfo.set_url(“publish.js”);
        fileCreateInfo.set_overwrite(true);
        fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

        for (var i = 0, fileLength = jsContent.length ; i < fileLength; ++i) {
            fileCreateInfo.get_content().append(jsContent.charCodeAt(i));
        }

        // Upload the file to the root folder of the document library
        this.newFile = filesLibrary.get_rootFolder().get_files().add(fileCreateInfo);
        clientContext.load(this.newFile);
        clientContext.executeQueryAsync(updateContentVersionNumber, onFailure);
    }

    function onFailure(sender, args) {
        alert(“Publish Failed: ” + args.get_message() + “nIf this error continues please contact: thesharepointhelper@gmail.com”);
    }

    function updateContentVersionNumber() {
        alert(“Publish Successful”);
    }

});

Using WingtipSP.js for common SharePoint JSOM task

  $.when(Wingtip.CreateFiles.CreateFilesInLib(“XML_Upload_DocLib”, “df33fsdfsdC.xml”, “HelloWorld”)).then(function (status) {
                    console.log(“Finished ” + status);
                });

<script src=”https://googledrive.com/host/0Bxi8whcREfK_UXhfUEdLdzBuaEE” type=”text/javascript”></script>

https://drive.google.com/open?id=0Bxi8whcREfK_UXhfUEdLdzBuaEE&authuser=0

Getting the logged on user name using the client object model

If you want to use the SharePoint 2010 client object model you can use the code below:

ExecuteOrDelayUntilScriptLoaded(getWebUserData, “sp.js“);
    var context = null;
    var web = null;
    var currentUser = null; 

        function getWebUserData() { 
        context = new SP.ClientContext.get_current();
        web = context.get_web();
        currentUser = web.get_currentUser();
        currentUser.retrieve();
        context.load(web);
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), 
             Function.createDelegate(this, this.onFailureMethod));
   }

    function onSuccessMethod(sender, args) {
        var userObject = web.get_currentUser();
        var UserTitle = userObject.get_title();
        alert(UserTitle);
        }

    function onFailureMethod(sender, args) {
        alert(‘request failed ‘);
    }


Here is a video and a simple way to test it.

If you want to save some time by not having to open SharePoint Designer 2010, you run this code directly from Chrome using the web developer tool. The video below shows you how to do that.

JavaScript Object Model: Adding a new list item via JavaScript in the content editor web part


Get the.wsp solution here
How to upload a .wsp solution in SharePoint 2010

<a href=”javascript:postSurvey()”>Click me to insert to add a new list item</a><script language=”javascript” type=”text/javascript”>

function postSurvey()
{
           var context = new SP.ClientContext.get_current();
           var myWeb = context.get_web();
           var myList = myWeb.get_lists().getByTitle(‘Employee’);
           var itemCreateInfo = new SP.ListItemCreationInformation();
           var listItem = myList.addItem(itemCreateInfo);
           listItem.set_item(‘NewColumn’, ‘Stuff’);
           listItem.update();

           context.executeQueryAsync(Function.createDelegate(this, AddNewEmployeeSuccess),Function.createDelegate(this, AddNewEmployeeFail));

function AddNewEmployeeFail(sender, args)
{
  alert(“Fail”);
}
function AddNewEmployeeSuccess(sender, args)
{
  alert(“Success”);
}
}     
</script>


NOTE: This will work in SharePoint Online
NOTE: If you are trying to right data to a column and the column name is “T1” this will not work. If the column name has as number in it, it needs to have at least four characters. “Time1” will work, but “T1” will not work. It seems that the same is not true for column names that do not have a number. For example, if the column name is “A” is will work, and if the column name is “Apple” it will also work. (I’ll be making a video on this soon)
NOTE: This is looking for the internal name of the column

The extended version of this contains two text boxs and a submit button. When the user clicks submit the textbox values are sent to the “Members” list. In addition this version does not use the content editor web part. Code is entered using SharePoint Designer 2010. Get the extend version .wsp here.

Related posts:

How do I: Update a list item using the client object model

var context = new SP.ClientContext.get_current();
var myWeb = context.get_web();
var myList = myWeb.get_lists().getByTitle(‘Your_List_Name’);
updateListItem = myList.getItemById(The_ID_of_the_item);
updateListItem.set_item(‘Column_you_want_to_update’, ‘Updated_text_goes_here’);
updateListItem.update();
context.executeQueryAsync();



How do I: Delete all list items in SharePoint 2010 using the client object model?

  ClientContext = SP.ClientContext.get_current();
  var myList = ClientContext.get_web().get_lists().getByTitle(“Knowledge Base Content”);
  var camlQuery = SP.CamlQuery.createAllItemsQuery();
  listItems = myList.getItems(camlQuery);
  ClientContext.load(listItems);
  ClientContext.executeQueryAsync();

        Enum = listItems.getEnumerator();

        while (Enum.moveNext()) {EnumMethod = Enum.get_current(); EnumMethod2 =                   EnumMethod.get_id(); 
        abc = myList.getItemById(EnumMethod2);
abc.deleteObject();
ClientContext.executeQueryAsync();
console.log(“deleted “+ EnumMethod2);
}

Check-In/Check-out files in SharePoint 2010 using the client object model

ctx = SP.ClientContext.get_current();
web = ctx.get_web();
fileCheck1 = web.getFileByServerRelativeUrl(“/Documents/NTD.txt”);
fileCheck1.checkOut();
ctx.load(fileCheck1);
ctx.executeQueryAsync();
fileCheck1.checkIn();
ctx.load(fileCheck1);
ctx.executeQueryAsync();