0

I am trying to get a random list item field from a sharepoint list. but the results return is undefined. The URL of the rest api is correct as i copy and past it directly to the browser it displays correct value.

Please see the code below

     window.myFunction = function() {
 var randomNumber = Math.floor(Math.random() * 320);  
alert('myFunction triggerred' + randomNumber);
//var listRandomURl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Wealoffortune')/items(4)?$select=Title&$top=1";
var listRandomURl = "https://mysite.sharepoint.com/sites/development2/_api/web/lists/GetByTitle('Wealoffortune')/items("+randomNumber+")/Actions";
alert(listRandomURl);

$.ajax({
   url: listRandomURl, 
   method: "GET",
   headers: { "Accept": "application/json; odata=verbose" },
   success: function (data) {
        alert(data.d.results);
   }
});
}


 
 fd.spRendered(function () {
 fd.control('Button1').onclick = "myFunction();";
});

Also i would like this to be shown in a label not in an alert how do i do that?

5
  • What is /Actions in your endpoint URL? Also, the item with ID equals to randomNumber should be present in list then only it will return the results. Commented Feb 3, 2021 at 12:33
  • Actions is a field, random number is present in the list as it will only generate less than 320 from the list which has 320 items). when I copy past the url from the alert(listRandomURl); directly to the web browser i am getting the results.
    – Rinu
    Commented Feb 3, 2021 at 12:37
  • Try using this: var listRandomURl = "https://mysite.sharepoint.com/sites/development2/_api/web/lists/GetByTitle('Wealoffortune')/items("+randomNumber+")?$select=Actions"; Commented Feb 3, 2021 at 12:42
  • Its still the same Ganesh
    – Rinu
    Commented Feb 3, 2021 at 13:00
  • Be advised that list item IDs increment and never reduce, and are not guaranteed to be contiguous. If, during the creation and set up of your list, any items were deleted, those list item IDs are no longer valid. E.g. if someone deleted what was ID 5, the new order goes ...3, 4, 6, 7..., and even if the total number of list items is 320, the top ID would now be 321 (since there is a gap where 5 used to be). List item IDs do not correlate with an indexer into the number of list items in the list. Commented Feb 3, 2021 at 15:18

2 Answers 2

2

The REST API endpoint /items(<itemId>) returns the list item data in data.d and not in data.d.results.

So, try changing your success function like this:

success: function (data) {
    console.log(data.d);
}

Here's working example where I am fetching Title of list item and showing it in label on DOM:

<p> Title:
    <label id="lblActions"></label>
</p>

<script type="text/javascript">
    $(document).ready(function() {
        getListItem(_spPageContextInfo.webAbsoluteUrl, 1);
    });

    function getListItem(url, itemId) {
        $.ajax({
            url: url + "/_api/web/lists/getbytitle('TestList')/items(" + itemId + ")?$select=Title",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if(data.d) {
                    $("#lblActions").text(data.d.Title);
                } else {
                    $("#lblActions").text("Item not found!");
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
</script>

Output:

enter image description here

5
  • 1
    Good point! I missed seeing that! :) Commented Feb 3, 2021 at 16:32
  • Thanks but now it says "[object Object]". Here is the full URL ,mysite.sharepoint.com/sites/development2/_api/web/lists/… and the output i get when past it in the browser and hit enter {"d":{"__metadata":{"id":"200f69c9-4717-422a-aaa6-dd4a4ba88dc6","uri":"mysite.sharepoint.com/sites/development2/_api/Web/…:"\"1\"","type":"SP.Data.WealoffortuneListItem"},"Actions":"Share a chocolate covered anything treat with others today"}}
    – Rinu
    Commented Feb 3, 2021 at 16:36
  • You can get Actions property by using data.d.Actions. Refer code in my updated answer. Commented Feb 3, 2021 at 16:40
  • Thank you Ganesh, Its working thanks
    – Rinu
    Commented Feb 3, 2021 at 18:58
  • @Rinu, do you also use range (with first and last ID) in your code? Because, if you get aleatory number out of the range of ID, this will break de code... Commented Feb 4, 2021 at 12:07
0

Please, define a range of randomNumber variable, corresponding with the first ID number and last ID number of your list items. MDN Web Docs contains a good example to extract a integer number between min and max range:

//Example extracted from https://developer.mozilla.org/en-us/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);

  //The maximum is exclusive and the minimum is inclusive
  return Math.floor(Math.random() * (max - min) + min); 
}

Then, refactoring your approach, will be like this:

window.myFunction = function(min, max) {
 var randomNumber = getRandomInt(min,max);  
alert('myFunction triggerred' + randomNumber);
//var listRandomURl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Wealoffortune')/items(4)?$select=Title&amp;$top=1";
var listRandomURl = "https://mysite.sharepoint.com/sites/development2/_api/web/lists/GetByTitle('Wealoffortune')/items("+randomNumber+")/Actions";
alert(listRandomURl);

$.ajax({
   url: listRandomURl, 
   method: "GET",
   headers: { "Accept": "application/json; odata=verbose" },
   success: function (data) {
        alert(data.d.results);
   }
});
}


 
 fd.spRendered(function () {
 fd.control('Button1').onclick = "myFunction();";
});
3

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.