0

I am trying to get the newest item added to a list.

Get item by ID works for single item:

$.ajax({
url: xurl + "/_api/web/lists('" + xlist + "')/items/getById(123)", 
type: "GET", headers: { "Accept": "application/json;odata=verbose", },
  success: function (data) {
    var xid = data.d.ID;
    alert(xid);},
  error: function (error) { alert(JSON.stringify(error)); }
});

Get top item, doesn't work, it returns undefined:

$.ajax({
url: xurl + "/_api/web/lists('" + xlist + "')/items?$top=1&$orderby=ID desc", 
type: "GET", headers: { "Accept": "application/json;odata=verbose", },
  success: function (data) {
    var xid = data.d.ID;
    alert(xid);},
  error: function (error) { alert(JSON.stringify(error)); }
});

Suggestions?

  • In your first code, you can also use the url as items(123). – sharepoint_geek Apr 19 at 19:32
  • faced the same issue. did the above comment work? – techrama Apr 20 at 7:30
5

The URL and endpoint seems right.

But in success, you will get the return data in data.d.results array.

So you can extract the ID of item from data.d.results array.

In this case, You will not get the ID of item directly using data.d.ID.

Try adding below code in success function:

if(data.d.results.length > 0) {
    var xid = data.d.results[0].ID;
    console.log(xid);
} 
  • Are you able to get the item ID using this code? – Ganesh Sanap Apr 19 at 19:27
  • per above, "/items" returns a collection of zero or more items. – Mike Smith - MCT - MVP Apr 19 at 19:46
  • nice! am learning, this site is the best resource ever! – BDC604 Apr 19 at 19:48
  • Yes, /items returns the collection. But using $top=1 will always return just single item. – Ganesh Sanap Apr 19 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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