Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

so if I use rest like method to create a list item in javascript, can I get the id of the newly created item in the callback/result function?

function createNewRecord(url, body, callback)
{
    $.ajax({
         type: 'POST',
         url: url,
         contentType: 'application/json',
         processData: false,
         data: body,
         success: function () {  callback(); }  
    });
}   

function createAnItem() {

  newItem = {};
  newItem.Title = 'Hello World';
  var body = Sys.Serialization.JavaScriptSerializer.serialize(newItem);
createNewRecord(urlVariable, body, onNewItemCallback);

}

function onNewItemCallback() {
     //is the id of the created item available here?
}

thanks! like response, response.get_responseData() from a GET request...or something like that?

share|improve this question
    
as far as I have been able to find anywhere, it doesn't? –  Justin Jul 28 '13 at 11:44
add comment

1 Answer

up vote 1 down vote accepted

The response from the POST message contains a JSON object representing the item that was just created. A reference to this object is passed as part of the first parameter to the success callback.

function createItem() {
    var due = new Date();
    due.setDate(due.getDate() + 7); // seven days from today

    jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Tasks')/Items",
        type: "POST",
        data: JSON.stringify({
            "__metadata": { type: "SP.Data.TasksListItem" },
            Title: "Sample Task",
            AssignedToId: _spPageContextInfo.userId,
            DueDate: due
        }),
        headers: {
            Accept: "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function (data, textStatus, jqXHR) {
            var itemId = data.d.Id;  // Id of new item

            var message = jQuery("#message");
            message.text("Item added. Id = " + itemId);
        }
    });
}
share|improve this answer
    
thanks a ton Rob. saved me a bunch of GETs as I was just unaware that each time I used this, the Id was already coming back :) –  Justin Aug 2 '13 at 10:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.