Friday, January 20, 2012

Returning new ID with SPServices 'UpdateListItems'

When using the results of SPServices there is a single line of code that saves an extra server call to either return the most recently added ID. That line is:

var newId = $(xData.responseXML).find("[nodeName='z:row']").attr("ows_ID");

The beautiful thing about this code is that it works in all browsers (no more checking if you're using Chrome and changing the nodeName to z\\:row), and it's faster than using another web service to return the new ID for you to use.

Here's a basic sample SPService call which uses it:

$().SPServices({
operation: "UpdateListItems",
listName: thisGrid.attr("ListName"),
batchCmd: "New",
async: false,
valuepairs: [
["Title", $('.edit-title-textbox', thisGrid).val() ],
["Description", $('.edit-description-textbox', thisGrid).val() ],
["Link", $('.edit-link-textbox', thisGrid).val() ],
["Image", $('.edit-image-textbox', thisGrid).val()]
],
completefunc: function(xData, Status) {
var newId = $(xData.responseXML).find("[nodeName='z:row']").attr("ows_ID");
thisGrid.find('.box-item[SharePointID=' + thisGrid.attr('SharePointID') + ']').attr('SharePointID', newId);
thisGrid.find('img[SharePointID=' + thisGrid.attr('SharePointID') + ']', newId);
thisGrid.attr('SharePointID', newId);
}
});

1 comment:

  1. Have to use SPFilterNode now. This works great.

    exsumId = $(xData.responseXML).SPFilterNode("z:row").attr("ows_ID");

    ReplyDelete