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?

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

1 Answer 1

4

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);
} 
4
  • Are you able to get the item ID using this code? Apr 19, 2019 at 19:27
  • per above, "/items" returns a collection of zero or more items. Apr 19, 2019 at 19:46
  • nice! am learning, this site is the best resource ever!
    – BDC604
    Apr 19, 2019 at 19:48
  • Yes, /items returns the collection. But using $top=1 will always return just single item. Apr 19, 2019 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.