SharePoint Online, 2013 and 2016 – Display list data in grid using Rest API

Hey Everyone!

Today, in this post i will show you how can we display list data in a grid using Rest API in SharePoint Online, 2013 and 2016.
In this example, i will create a table – Cars – with 4 columns:

– Make
– Model
– Price
– Color

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
    $("#btnClick").click(function(){
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Cars')/items";
           $.ajax({
              url: requestUri,
              type: "GET",
              headers: {
                  "accept":"application/json; odata=verbose"
              },
              success: onSuccess,
              error: onError
});

  function onSuccess(data) {
     var objItems = data.d.results;
     var tableContent = '<table id="tableCars" style="width:100%" border="1 px"><thead><tr><td>Make</td>' + '<td>Model</td>' + '<td>Price</td>' + '<td>Color</td>' + '</tr></thead><tbody>';
  
     for (var i = 0; i < objItems.length; i++) {
         tableContent += '<tr>';
         tableContent += '<td>' + objItems[i].Make  + '</td>';
         tableContent += '<td>' + objItems[i].Model + '</td>';
         tableContent += '<td>' + objItems[i].Price + '</td>';
         tableContent += '<td>' + objItems[i].Color + '</td>';
         tableContent += '</tr>';
 }
   $('#carsGrid').append(tableContent);
   }
    function onError(error) {
        alert('Error');
   }
  });
});

</script>
<input type="button" id="btnClick" value="Get All Cars"/>
<div id="CustomerPanel">
   <table id='tableCars' style="width: 100%;" border="1 px">
     <tr>
       <td>
          <div id="carsGrid" style="width: 100%"></div>
      </td>
    </tr>
 </table>
</div>

You just need to copy the code and past in a script editor webpart, if you press the button  – Get All Cars –  the result it’s a the following table:

MarkModelPriceColor
MercedesA18022.000.00€Red
JaguarX-Type72.000.00€Green
Fiat50020.000.00€Blue
Bmw320d32.000.00€Black

If you are interested to read more, i recommend the following links:
https://msdn.microsoft.com/en-us/library/office/jj860569.aspx
https://msdn.microsoft.com/en-us/library/office/jj164022.aspx

Thanks

Fábio Carvalho
SharePoint Consultant
|create|it|

Leave a Reply

Your email address will not be published. Required fields are marked *