How to: Get List Data using REST and JQuery – SharePoint 2013

This article is inspiration from Corey Roth’s article “How to: Query SharePoint 2013 using REST and Javascript“, where REST api is used to get the search results from the search textbox input.

Here we are querying the list data using REST and JQuery and post the results in the html table format.  For simplicity we are using Script Editor to show the results.

Step 1:

Edit the Page and add Script Editor Web Part to the page.

Step 2:

Add a div tag with id, which will be used later to show the results in table format.

<div id=”resultsDiv”></div>

Step 3:

Add the JQuery reference so that the JQuery will be used in the code.  For simplicity we are referring directly from JQuery site, you can add JQuery library to library in SharePoint and refer from there.

<script src=”//code.jquery.com/jquery-1.10.2.js”></script>

Step 4:

Use the following code to get the Client Context after loading the required JS files.

    SP.SOD.executeFunc(“sp.js”, “SP.ClientContext”, function (){
        SP.SOD.executeFunc(“sp.runtime.js”, “SP.ClientContext”, function () {
            var context = SP.ClientContext.get_current();
        });
    });

The following is the complete code for the reference.

<div id=”resultsDiv”></div>
<script src=”//code.jquery.com/jquery-1.10.2.js”></script>
(function($, undefined) {
  SP.SOD.executeFunc(“sp.js”, “SP.ClientContext”, function() {
    SP.SOD.executeFunc(“sp.runtime.js”, “SP.ClientContext”, function() {
      var context = SP.ClientContext.get_current();
      var queryUrl = “https://aataaq.sharepoint.com/_api/web/lists/getbytitle(‘Orders’)/items”; //change the Url
      $.ajax({
        url: queryUrl,
        method: “GET”,
        headers: {
          “Accept”: “application/json; odata=verbose”
        },
        success: onQuerySuccess,
        error: onQueryError
      });
    });
  });
  function onQuerySuccess(data) {
    var results = data.d.results;
    $(“#resultsDiv”).append(‘<table>’);
    $(“#resultsDiv”).append(‘<tr><td style=”font-weight:bold”>Order No</td><td style=”font-weight:bold”>Part No</td><td style=”font-weight:bold”>Quantity</td></tr>’); //add more heading columns as per your requirement.
    $.each(results, function(index, dataRec) {
      $(“#resultsDiv”).append(‘<tr>’);
      $(“#resultsDiv”).append(‘<td>’ + dataRec.Title + ‘</td>’); //Add more columns as per your requirement.
      $(“#resultsDiv”).append(‘<td>’ + dataRec.Part_x0020_No + ‘</td>’);
      $(“#resultsDiv”).append(‘<td>’ + dataRec.Order_x0020_Qty + ‘</td>’);
      $(“#resultsDiv”).append(‘</tr>’);
    });
    $(“#resultsDiv”).append(‘</table>’);
  }
  function onQueryError(error) {
    $(“#resultsDiv”).append(error.statusText)
  }
})(jQuery);

Final result will be as per the following screenshot.

REST_JQUERY

Happy Coding…

 

This entry was posted in SharePoint 2013. Bookmark the permalink.

Leave a Reply