6

I try to update my sharepoint list using REST api. But following code throws exception in browser "Uncaught ReferenceError: etag is not defined " Can someone help to resolve this issue?

 // update an item 
    var requestUri = _spPageContextInfo.webAbsoluteUrl + '/_api/Web/Lists/getByTitle(\'Suppliers\')/items(1)';
    var requestHeaders = { 'Accept': 'application/json;odata=verbose', 
        'X-RequestDigest': $('#__REQUESTDIGEST').val(), 
        'X-HTTP-Method': 'MERGE', 
        'If-Match': etag }; 
    var customerData = { __metadata: { 'type': 'SP.Data.ContactsListItem' }, Title: 'NewName', }; 
    requestBody = JSON.stringify(customerData); 
    $.ajax({ url: requestUri, type: 'POST', 
        contentType: 'application/json;odata=verbose', headers: requestHeaders, 
        data: JSON.stringify(customerData)
    ,
    success: function (response)
    { alert('Success');
    }, 
    error: function(error)
    { 
        alert('error');
    } 
    });
4
  • 2
    try "IF-MATCH": "*"
    – Aanchal
    Commented Sep 22, 2014 at 11:56
  • 1
    It may help to show where you specify your variable etag.
    – wjervis
    Commented Sep 22, 2014 at 12:08
  • @Aanchal Now, 'Failed to load resource: the server responded with a status of 400 (Bad Request)'. But URL is working fine. Commented Sep 22, 2014 at 12:11
  • When I try to run the sample, I get the following in Google Chrome's developer tools, console window: Failed to load resource: the server responded with a status of 400 (Bad Request) XMLHttpRequest cannot load XXX:1000/_api/Web/Lists/getByTitle(\'Suppliers\')/items(1). Commented Sep 22, 2014 at 12:56

1 Answer 1

21

This error occurs since tag variable is not defined.

About eTag

When updating or deleting items within SharePoint lists via REST you must specify the Entity Tag (eTag) value that was returned with the item during the initial query. This enables SharePoint to determine if the item has changed since it was requested. Alternatively you can tell SharePoint to perform the operation regardless by specifying * as the eTag value. For example:

  • If-Match: item.__metadata.etag can be used to specify the actual eTag value (‘item’ is the object returned from SharePoint containing
    the list item in JSON format).
  • If-Match: * can be used to match any eTag value resulting in the operation being performed regardless of the actual value.

How to update List Item via SharePoint REST interface

function updateJson(endpointUri,payload, success, error) 
{
    $.ajax({       
       url: endpointUri,   
       type: "POST",   
       data: JSON.stringify(payload),
       contentType: "application/json;odata=verbose",
       headers: { 
          "Accept": "application/json;odata=verbose",
          "X-RequestDigest" : $("#__REQUESTDIGEST").val(),
          "X-HTTP-Method": "MERGE",
           "If-Match": "*"
       },   
       success: success,
       error: error
    });
}

function getItemTypeForListName(name) {
    return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}

function updateListItem(webUrl,listTitle,listItemId,itemProperties,success,failure)
{
     var listItemUri =  webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")";
     var itemPayload = {
       '__metadata': {'type': getItemTypeForListName(listTitle)}
     };
     for(var prop in itemProperties){
           itemPayload[prop] = itemProperties[prop];
     }
     updateJson(listItemUri,itemPayload,success,failure);
}

Usage

var itemProperties = {'Title':'John Doe'};
updateListItem(_spPageContextInfo.webAbsoluteUrl,'Contacts',1,itemProperties,printInfo,logError);
function printInfo()
{
    console.log('Item has been created');
}
function logError(error){
    console.log(JSON.stringify(error));
}

References

Manipulating list items in SharePoint Hosted Apps using the REST API

3
  • 1
    Good explanation about Manipulating list items in SharePoint using the REST API. Thanks @Vadim Commented Sep 23, 2014 at 5:12
  • hello I am getting 204 response code.why can you please tell me?its updated item successfully but why not give 200 response code. i am passing etag " * " in header and method merge then why i get this response code ?? how to resolve this. its show no content but what exact mean of it what i am doing wrong Commented Apr 8, 2016 at 10:16
  • 1
    eeeehm the getItemTypeForListName(name) function does not return the correct format for a custom List.
    – Snickbrack
    Commented Dec 8, 2016 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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