Creating List Items with jQuery and the SharePoint Web Services

In my previous post I showed how to make a call to SharePoint’s Lists.asmx web service with the jQuery library to retrieve information about the Lists and Document Libraries that are available on a specific SharePoint Site. In the comments of that post, one of the readers asked if it would be possible to create a new item in a List using the same technique. Of course this is possible, you just need to make use of the UpdateListItems web method (yeah, the name of that method is not very intuitive). Here is a quick example!

First let’s create the UI (in this example I'll use a basic Site Page) to allow the user to enter a Title for the new task, and a button to do the action.

<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderMain">
    <p>
        Task Title:
        <input id="newTaskTitle" type="text" />
        <input id="newTaskButton" type="button" value="Create Task" />
    </p>
</asp:Content>

Next let’s create a Javascript function that will create a new item in a Task list. In the Javascript function I’m declaring two variables that will contain the XML which will be sent to the SharePoint Lists.asmx web service. The first variable (I called it batch) contains the CAML to create a new item. For simplicity the CAML only provides a value for the Title field, add more fields if you’d like. The second variable (called soapEnv) is the SOAP Envelope XML which wraps the batch XML. Notice that in the SOAP Envelope the name of the list is mentioned in which we’re going to create a new item (in this case the Task list). Finally the jQuery ajax function is used to POST the data to the Lists.asmx web service. (If you test this code make sure you update the url option with the URL of your site).

function CreateNewItem(title) {
    var batch =
        "<Batch OnError=\"Continue\"> \
            <Method ID=\"1\" Cmd=\"New\"> \
                <Field Name=\"Title\">" + title + "</Field> \
            </Method> \
        </Batch>";

    var soapEnv =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
        <soap:Envelope xmlns:xsi=\"
http://www.w3.org/2001/XMLSchema-instance\" \
            xmlns:xsd=\"
http://www.w3.org/2001/XMLSchema\" \
            xmlns:soap=\"
http://schemas.xmlsoap.org/soap/envelope/\"> \
          <soap:Body> \
            <UpdateListItems xmlns=\"
http://schemas.microsoft.com/sharepoint/soap/\"> \
              <listName>Tasks</listName> \
              <updates> \
                " + batch + "</updates> \
            </UpdateListItems> \
          </soap:Body> \
        </soap:Envelope>";

    $.ajax({
        url: "
http://yoursite/_vti_bin/lists.asmx",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("SOAPAction",
            "
http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
        },
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=utf-8"
    });
}

The jQuery ajax function call has a complete option which points to a function, in this function you can process the result as follows:

function processResult(xData, status) {
    alert(status);
}

The status parameter is a string which can be for example success or error. Finally in the ready event of the document, we'll hook up the click event of the button so the CreateNewItem function is called, with the value of the textbox as the parameter.

$(document).ready(function() {
    $("#newTaskButton").click(function() {
        CreateNewItem($("#newTaskTitle").val());
    });
});
 

That’s it! If you put all the code in a simple Site Page, upload the page to a Document Library in a SharePoint site, and now you can create Task list items by only using Javascript! The sample code can be downloaded in the following zip file. The zip file also contains the jQuery library which you can upload to the same Document Library if it isn't already loaded with the help of the SmartTools.jQuery component for example.

7 Comments

  • I don't think this will appear in the comments, but I can try...

    var wsUrl = window.location.protocol+"//"+window.location.hostname+L_Menu_BaseUrl+"/_vti_bin/lists.asmx";

    $.ajax({
    url: wsUrl,
    ...

    Now the URL is built based on page context, no need to modify the URL.

  • Works like a champ!

  • I was trying to get items from a list rather than update. Any ideas on how that could be done?

  • Hi Jan,

    Astonishing technique! Really enjoyed that!

    But what about security, permissions, impersonation ...? How come we can put some JavaScript and modify the list? Is the Web Service called in the security context of the currently logged in user? It should be like this.

    I did not bother to ask this question in your previous post when we were only reading data but this time the technique went too powerful.


    Cheers,
    Lubo

  • @Lubo: The underlying XmlHttpRequest in Javascript will automatically use the credentials of the currently logged on user in the browser instance. So I don't see a security issue. :-)

  • Jan,

    I am having an issue, when I put in an "&" in to the title it will error out.

    Are you having this issue and do know a fix for it?

    Thanks,

    Peter

  • Hi Jan...

    Thank you so much.. excellent work :) It works well for me without any errors.

Comments have been disabled for this content.