Function

$().SPServices

Web Service

Lists

Operation

UpdateListItems

Notes

  • This operation accepts a webURL option. This allows you to change the context for the operation to a different site. Using a GUID for the listName does NOT change the context as it does with the Object Model, so you need to use the webURL option as well if your list is in a different site.

Additional Syntax

If you want to update a single list item, rather than using the CAML syntax in updates you can specify valuepairs and the item's ID. If you specify valuepairs then updates should not be specified. The way it works is that it lets you specify an array of column StaticNames and values. So if you wanted to update the Title and the Body:

batchCmd: "Update",
valuepairs: [["Title", "New Title Value"], ["Body", "Here is a the new text for the body column."]],
ID: 1234,

All that happens here is that the valuepairs are used to build up the CAML for UpdateListItems rather than requiring you to specify the full CAML syntax, which in this case would be:

<Batch OnError='Continue'>
  <Method ID='1' Cmd='Update'>
    <Field Name='Title'>New Title Value</Field>
    <Field Name='Body'>Here is a the new text for the body column.</Field>
    <Field Name='ID'>1234</Field>
  </Method>
</Batch>

Note that if you decide to use the valuepairs approach, you also need to specify the ID option. The default for the batchCmd option is 'Update'. Also, the choices for Cmd are [New, Update, Delete, Moderate].

Examples

This is an example from my test harness. If you have a better, real life example, please post it in the Discussions.

$(divId).html(waitMessage).SPServices({
	operation: "UpdateListItems",
	listName: testList,
	ID: ID,
	valuepairs: [["Title", now]],
	completefunc: function (xData, Status) {
		var out = $().SPServices.SPDebugXMLHttpResult({
			node: xData.responseXML,
			outputId: divId
		});
		$(divId).html("").append("<b>This is the output from the UpdateListItems operation:</b>" + out);
		$(divId).append("<b>Refresh to see the change in the list above.</b>");
	}
});


Here's an example of creating a folder in a Document Library using the PreSaveAction which came from a discussion with LeSanglier. (The PreSaveAction is called when the form is submitted and is a useful place to put business logic.)

<script language="javascript" type="text/javascript" src="/HRD/JQuery/jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/HRD/JQuery/spservices/jquery.SPServices-0.4.7.min.js"></script>

<script language="javascript" type="text/javascript" >
function PreSaveAction() {
    var folderName = "essai";
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        listName: "documents",
        updates: "<Batch OnError='Continue' PreCalc='TRUE'>" +
                "<Method ID='1' Cmd='New'>" +
                    "<Field Name='FSObjType'>1</Field>" +
                    "<Field Name='BaseName'>" + folderName + "</Field>" +
                "</Method>" +
            "</Batch>",
        completefunc: function(xData, Status) {
            …
        }
    });
    return true;
}</script>

Another example from _tomdaly_. This example takes advantage of the valuepairs notation, which is part of SPServices. The List Web Service itself requires the Batch notation shown above.

This is an example of adding a new list item from a simple feedback type form.

$(document).ready(function() { $("#feedback-submit input").click(function() { var subject = $("#feedback-subject-input input").val(); var message = $("#feedback-message-input textarea").text(); CreateNewItem(subject, message); }); }); function CreateNewItem(subject, message) { $().SPServices({ operation: "UpdateListItems", async: false, batchCmd: "New", listName: "Feedback", valuepairs: [["Title", subject], ["Message", message]], completefunc: function(xData, Status) { alert("completed"); } });
}

Last edited Sep 16, 2012 at 4:12 PM by sympmarc, version 12

Comments

NetricSolutions Nov 20, 2012 at 10:48 AM 
Hi Marc,

Awesome library! Reading from lists with SPS is working great. But my first attempt at writing to a list is not turning out so hot. I wonder if you could help me diagnose the problem. It sure looks like I have everything set up correctly.

I am using UpdateListItems. After calling the function, a new item has indeed been added; I get a correct ID back. But back on the SP list, all of the fields are blank. The Title field has a standard "(no title)" text in it.

After unsuccessfully using an existing list, I made a basic custom list with just the Title field. The list is called SPServices. When using lists with more fields, all of those fields are blank as well.

I can enter a new item from the browser. I am a site collection admin, and permissions are all proper.



Here's the call:
$().SPServices({
operation: "UpdateListItems",
asynch: false,
batchCmd: "New",
listName: "SPServices",
valuePairs: [ ["Title", "JS Entry"] ],
completefunc: function(xData, Status){
r.append(Status+"...");
var newId = $(xData.responseXML).SPFilterNode("z:row").attr("ows_ID");
r.append("New ID : "+newId+"...");
},
debug: true
});


Here's the Request / Response traffic (slightly redacted:

==========
Webs.asmx
==========
Request Headers
Key Value
Request POST /_vti_bin/Webs.asmx HTTP/1.1
Accept application/xml, text/xml, */*; q=0.01
Content-Type text/xml;charset="utf-8"
X-Requested-With XMLHttpRequest
Referer https://domain.mil/sites/subsite/sps.htm
Accept-Language en-us
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)
Host domain.mil
Content-Length 383
Connection Keep-Alive
Cache-Control no-cache
Cookie WSS_KeepSessionAuthenticated=443; MSOWebPartPage_AnonymousAccessCookie=443

Request Body
<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>
<WebUrlFromPageUrl xmlns='http://schemas.microsoft.com/sharepoint/soap/' >
<pageUrl>https://domain.mil/sites/subsite/sps.htm</pageUrl>
</WebUrlFromPageUrl>
</soap:Body>
</soap:Envelope>

Response Headers
Key Value
Response HTTP/1.1 200 OK
Cache-Control private, max-age=0
Content-Length 460
Content-Type text/xml; charset=utf-8
Server Microsoft-IIS/6.0
MicrosoftSharePointTeamServices 12.0.0.6550
X-Powered-By ASP.NET
X-AspNet-Version 2.0.50727
Date Tue, 20 Nov 2012 11:09:58 GMT

Response Body
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<WebUrlFromPageUrlResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<WebUrlFromPageUrlResult>https://domain.mil/sites/subsite</WebUrlFromPageUrlResult>
</WebUrlFromPageUrlResponse>
</soap:Body>
</soap:Envelope>

==========
Lists.asmx
==========
Request Headers
Key Value
Request POST /sites/subsite/_vti_bin/Lists.asmx HTTP/1.1
Accept application/xml, text/xml, */*; q=0.01
Content-Type text/xml;charset='utf-8'
SOAPAction http://schemas.microsoft.com/sharepoint/soap/UpdateListItems
X-Requested-With XMLHttpRequest
Referer https://domain.usmc.mil/sites/subsite/sps.htm
Accept-Language en-us
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)
Host domain.mil
Content-Length 415
Connection Keep-Alive
Cache-Control no-cache

Request Body
<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>SPServices</listName>
<updates>
<Batch OnError='Continue'>
<Method ID='1' Cmd='New'></Method>
</Batch>
</updates>
</UpdateListItems>
</soap:Body>
</soap:Envelope>

Response Headers
Key Value
Response HTTP/1.1 200 OK
Cache-Control private, max-age=0
Content-Length 1802
Content-Type text/xml; charset=utf-8
Server Microsoft-IIS/6.0
MicrosoftSharePointTeamServices 12.0.0.6550
X-Powered-By ASP.NET
X-AspNet-Version 2.0.50727
Date Tue, 20 Nov 2012 11:09:59 GMT

Response Body
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<UpdateListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<UpdateListItemsResult>
<Results>
<Result ID="1,New">
<ErrorCode>0x00000000</ErrorCode>
<ID />
<z:row ows_ID="12" ows_ContentTypeId="0x0100449D605E99E81F43837C4964549392A2"
ows_ContentType="Item" ows_Modified="2012-11-20 05:09:59" ows_Created="2012-11-20 05:09:59"
ows_Author="44;#Doe LtCol John J" ows_Editor="44;#Doe LtCol John J"
ows_owshiddenversion="1" ows_WorkflowVersion="1" ows__UIVersion="512" ows__UIVersionString="1.0"
ows_Attachments="0" ows__ModerationStatus="0"
ows_SelectTitle="12" ows_Order="1200.00000000000"
ows_GUID="{BDD70366-11E8-40CC-B057-3996041D8791}"
ows_FileRef="12;#sites/subsite/Lists/SPServices/12_.000" ows_FileDirRef="12;#sites/subsite/Lists/SPServices"
ows_Last_x0020_Modified="12;#2012-11-20 05:09:59"
ows_Created_x0020_Date="12;#2012-11-20 05:09:59" ows_FSObjType="12;#0" ows_PermMask="0x7fffffffffffffff"
ows_FileLeafRef="12;#12_.000"
ows_UniqueId="12;#{7CC88A51-8A69-4955-BD69-8838A28B48B7}"
ows_ProgId="12;#"
ows_ScopeId="12;#{11C9F797-9460-4544-B21C-8A1F6B2848E2}"
ows__EditMenuTableStart="12_.000" ows__EditMenuTableEnd="12" ows_LinkFilenameNoMenu="12_.000"
ows_LinkFilename="12_.000" ows_ServerUrl="/sites/subsite/Lists/SPServices/12_.000"
ows_EncodedAbsUrl="https://domain.mil/sites/subsite/Lists/SPServices/12_.000"
ows_BaseName="12_" ows_MetaInfo="12;#" ows__Level="1" ows__IsCurrentVersion="1"
xmlns:z="#RowsetSchema" />
</Result>
</Results>
</UpdateListItemsResult>
</UpdateListItemsResponse>
</soap:Body>
</soap:Envelope>



Sorry for the length of the comment, but you probably would want this for diagnosis. This is an awesome library..if I can get it to write back!! I'd like to make EXTENSIVE use of it.

Thanks in advance,

Ed

kantboy Nov 12, 2012 at 2:44 PM 
Hi Marc, I'm trying to set something up that will display a link on each row of a view, which when clicked will add the current user to a multiple person column for that item, or remove the current user if already there. I'm using it for a feature that allows a user to 'favourite' a document. It looks like your UpdateListItems could be what I need (I already have SPServices installed). I'm quite new to all this and am having trouble understanding the examples above - can you explain a little further how I might go about this (without removing the names that are already there)? I think my code should probably most closely resemble the last example. Something like this (sorry, I know this isn't right at all)?

$(document).ready(function() {
$("#AddRemoveFavourite").click(function() {

var username = $UserId;

UpdateItem(username);

});
});

function UpdateItem(username) {
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "Update",
listName: "Reports",
valuepairs: [["Favourite", username],
completefunc: function(xData, Status) {
alert("completed");
}
});
}