Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint / SharePoint2010

How to Insert into and Update Sharepoint 2010 Lists with jQuery

0.00/5 (No votes)
20 Oct 2015CPOL2 min read 7.6K  
Inserting and Updating Sharepoint 2010 Lists from the Client, using Javascript/jQuery

Creating and Updating Sharepoint 2010 Lists from the Other Side of the Aisle or Isle

Six months ago, I wrote a tip entitled "How to Create, Write to, and Read From Sharepoint 2010 Lists with C#." You can gawk at it here

If you need or prefer to work as much with client code (Javascript/jQuery) as possible (as opposed to working as much with the code-behind C# as possible, as that previous tip had as its premise), you might enjoy this tip, which demonstrates the former, Javascript-centric methodology.

The first thing you have to do in any situation is to follow Bruce Springsteen's musical advice and "give it a name." So first give your List a name. To do so, put this within your WebPart class (prior to the constructor or any other methods):

public string listTitle = "dPlatypus"; // or some other name, if necessary

Give your list whatever name you want, but preferably something descriptive and unique.

Since we are going to (conditionally - that is, once and once only) create a Sharepoint list, write to the list and read from it, we should start by defining the structure of the list itself. We do this by creating a separate class, such as this one (in C#, in the *.ascx.cs file):

public class PostTravelFormFields
{
    // page 1
    public DateTime ptli_formFilledOut { get; set; }
    public string ptli_TravelersName { get; set; }
    public string ptli_TravelersEmail { get; set; }
    public string ptli_TravelersPhone { get; set; }
    public string ptli_TravelersMailstop { get; set; }
    public string ptli_TravelersStreetOrPO { get; set; }
    public string ptli_TravelersDestination { get; set; }
    public string ptli_BusinessPurpose { get; set; }
    public DateTime ptli_dtDeparture { get; set; }
    . . .
}

Of course, you will have different members of your list.

Now for the interesting parts, or the "nitty-gritty" (Yeah, Dirt Band!). The "rubber meats the road" when the user does something with the data, like so (this is jQuery):

var _TravelersName;
var _TravelersEmail;
var _TravelersPhone;
var _TravelersMailstop;
var _TravelersStreetOrPOBox;
var _TravelersDestination;
var _BusinessPurpose;
var _dtDeparture;
. . .
_TravelersName = $('#travelername').val();
_TravelersEmail = $('#traveleremail').val();
_TravelersPhone = $('#travelerphone').val();
_TravelersMailstop = $('#travelermailstop').val();
_TravelersStreetOrPOBox = $('#travelerstreetorpobox').val();
_TravelersDestination = $('#travelersdestinations').val();
_BusinessPurpose = $('#ucbusinesspurpose').val();
_dtDeparture = $('#travelersdeparturedate').val();
upsertPostTravelListItemTravelerInfo1();

The values such as "#travelername" reference html elements with the corresponding IDs, of course. And here's the Upsert jQuery method called from above:

function upsertPostTravelListItemTravelerInfo1() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    this.website = clientContext.get_web();
    currentUser = this.website.get_currentUser();

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);

    var travelersEmail = $('#traveleremail').val();
    var departureDate = $('#travelersdeparturedate').val();

    /* If this is an update, the call to setListItemID() will return a val; otherwise (an insert), get from newly instantiated 

ListItem.  */
    setListItemID(currentUser, travelersEmail);
    /* The Id is gotten asynchronously, so wait a bit before trying to access it */
    setTimeout(function () {
        var b = 42; 
    }, 3000);

    if (listId === '') {
        listId = this.oListItem.ID;
    }

    oListItem.set_item('Title', currentUser + '_' + travelersEmail + '_' + departureDate);
    oListItem.set_item('ptli_formFilledOut', $('#formfilledout').val()); /* new Date()); */
    oListItem.set_item('ptli_preparerEmail', currentUser);
    oListItem.set_item('ptli_TravelersName', $('#travelername').val());
    oListItem.set_item('ptli_TravelersEmail', travelersEmail);
    oListItem.set_item('ptli_TravelersPhone', $('#travelerphone').val());
    oListItem.set_item('ptli_TravelersMailstop', $('#travelermailstop').val());
    oListItem.set_item('ptli_TravelersStreetOrPO', $('#travelerstreetorpobox').val());
    oListItem.set_item('ptli_TravelersDestination', $('#travelersdestinations').val());
    oListItem.set_item('ptli_BusinessPurpose', $('#ucbusinesspurpose').val());
    oListItem.set_item('ptli_dtDeparture', departureDate);
    oListItem.set_item('ptli_dtReturn', $('#travelersreturndate').val());

    oListItem.update();

    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, 

this.onQueryFailed));
}

Here is the helper function to set the ListItemId:

/* From http://stackoverflow.com/questions/33047426/how-can-i-determine-if-a-sharepoint-listitem-exists-based-on-a-couple-of-

known-v  and 
        http://stackoverflow.com/questions/33091343/why-am-i-getting-uncaught-typeerror-getenumerator-is-not-a-

function/33111315#33111315 */

function setListItemID(username, payeename) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    /* Use a CAML query to filter your results */
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ptli_TravelersEmail\' /><Value Type=\'Text\'>' + payeename 

+ '</Value></Eq></Where></Query></View>');

    /* get the list item collection from the list */
    var oListItems = oList.getItems(camlQuery);

    /* tell SharePoint to load the list items */
    clientContext.load(oListItems);

    /* execute the query to get the loaded items */
    clientContext.executeQueryAsync(
    /* onSuccess Function */
        Function.createDelegate(this, function () {
           /* 
            now that the query has run, you can get an enumerator 
            from your list item collection 
            */
        var arrayListEnum = oListItems.getEnumerator();
        var ids = [];
        while (arrayListEnum.moveNext()) {
            var listItem = arrayListEnum.get_current();
            ids.push(listItem.get_id());
        }
        if (ids.length > 0) {
            listId = ids[0];
        }
        else {
                    listId = '';
                }
        }),
        /*onFailure Function*/
        Function.createDelegate(this, function (sender, args) {
            alert("Whoops: " + args.get_message() + " " + args.get_stackTrace());
        })
    );
}

There is some more C# code that I have retained, even in this Javascript-centric tip. Specifically, it is to conditionally create the list (also in the *.ascx.cs file, like the list definition class):

private void ConditionallyCreateList()
{
    SPWeb site = SPContext.Current.Web;
    site.AllowUnsafeUpdates = true;
    // Check to see if list already exists; if so, exit
    if (site.Lists.TryGetList(listTitle) != null) return;

    SPListCollection lists = site.Lists;
    SPListTemplateType listTemplateType = new SPListTemplateType();
    listTemplateType = SPListTemplateType.GenericList;
    string listDescription = "This list retains vals inputted for the Post Travel form";
    Guid ListId = lists.Add(listTitle, listDescription, listTemplateType);

    SPList list = site.Lists[ListId];
    list.OnQuickLaunch = true;

    // The list's "title" field is auto-added
    list.Fields.Add("ptli_listCollectionId", SPFieldType.Guid, false);
    list.Fields.Add("ptli_formFilledOut", SPFieldType.DateTime, false);
    list.Fields.Add("ptli_TravelersName", SPFieldType.Text, false);
    list.Fields.Add("ptli_TravelersEmail", SPFieldType.Text, false);
    list.Fields.Add("ptli_TravelersPhone", SPFieldType.Text, false);
    list.Fields.Add("ptli_TravelersMailstop", SPFieldType.Text, false);
    list.Fields.Add("ptli_TravelersStreetOrPO", SPFieldType.Text, false);
    list.Fields.Add("ptli_TravelersDestination", SPFieldType.Text, false);
    list.Fields.Add("ptli_BusinessPurpose", SPFieldType.Text, false);
    list.Fields.Add("ptli_dtDeparture", SPFieldType.DateTime, false);
    . . .

Now to update the existing list, the assignment code is of the same ilk; the posting code only slightly differs:

function upsertPostTravelListItemTravelerInfo2() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
    this.oListItem = oList.getItemById(listId);
    . . .

As you can see, the existing list is used, so that the same list already inserted into is updated, as opposed to a new one. listId is a var that is defined and used this way:

var listId;
. . .
// from upsertPostTravelListItemTravelerInfo1:
this.oListItem = oList.addItem(itemCreateInfo);
. . .
if (listId === '') {
    listId = this.oListItem.ID;
}

// from upsertPostTravelListItemTravelerInfo2 (again):
this.oListItem = oList.getItemById(listId);   

And so the first time (the insert), the generated and returned id is used; after that, that same saved value is used, so that the list is being updated.

Und damit basta (that's a German sermon, not a Russian cussin')

That should work (it does for me); however, programming being what it is, and perhaps Sharepoint in particular, you will probably run into some problems - IOW, don't expect it to work perfectly the first time. So remember: google and/or bing are your friends.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)