I am having problems updating list items using REST calls within an angularjs SPA. I've tried HTTP and ajax methods but both do not work and give different errors. (I am only trying to update Description with some static text to prove it works.)
Both ways are contained in a factory service:
testLabApp.factory('service', ['$http', function ($http) {
var updateBooking = function (booking, callback) {
....HTTP/AJAX REST code here...
}
return {
updateBooking: updateBooking
}
}]);
HTTP
$http({
method: 'POST',
url: "/_api/web/lists/GetByTitle('Bookings')/items(" + booking.Id + ")",
body: { '__metadata': { 'type': 'SP.Data.BookingsListItem' }, 'Description': 'Description Updated' },
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE",
accept: "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
}
}).success(function (data) {
console.log("[updateBooking] POST worked");
console.log('[updateBooking] Id = ' + data.Id);
callback(data);
}).error(function (er) {
console.log('[updateBooking] Error = ' + er);
});
};
I get an error 415 Media Type wrong but answers online say add 'Content-Type' header which I have done. Unless it is wrong ?!
AJAX
ajax seems to be a common way to make REST calls and I borrowed this from another POST on SharePoint StackExchange which had similar problem.
$.ajax({
url: "/teams/technology-cell-79-new-stores-retail-implementations/testing/testlab/_api/web/lists/GetByTitle('Bookings')/items(" + booking.Id + ")",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.BookingsListItem'
},
'Description': 'Description Updated'
}),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log('[ajax update success] ' + JSON.stringify(data.d));
alert("Update successful.");
callback(data);
},
error: function (err) {
console.log(JSON.stringify(err));
alert("Update failed")
}
});
The app returns an error:
{ "readyState": 4, "responseText": "{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.InvalidClientQueryException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The parameter __metadata does not exist in method GetById.\"}}}", "responseJSON": { "error": { "code": "-1, Microsoft.SharePoint.Client.InvalidClientQueryException", "message": { "lang": "en-US", "value": "The parameter __metadata does not exist in method GetById." } } }, "status": 400, "statusText": "Bad Request" }
Which I do not understand as there is no getById
call in the request.
Any suggestions please?
{"Description" : "Description updated."}
as your body, and setContent-Type
toapplication/json; odata=nometadata
. This isn't a solution, I'm just curious of JSON light works. If it doesn't, you need to double check your url's. Also, you don't mention apps anywhere, so I'm assuming that this is not an app.