Rest API Get Method Using jQuery Template In SharePoint 2013

Welcome to a blog on getting the data from a list and putting the data in a template. Here, we will discuss a step by step procedure to get the data from a list and place it in a template

Here, the main code to get the data from a list in detail is given below. 

  1.     var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/GetByTitle ('list name')/Items";  
  2.         
  3.         // Getting our list items  
  4.         $.ajax({  
  5.             url: requestUrl,  
  6.             type: "GET",  
  7.             async: false,  
  8.             headers: { "Accept""application/json; odata=verbose" },  
  9.             success: function (data) {  
  10.                 // Returning the results  
  11.                
  12.                 $.each(data.d.results, function (index, item) {  
  13. //Append data to the template  
  14.                     $("#empTemplate").tmpl(item).appendto("#tbDetails");  
  15.                 });  
  16.             },  
  17.             error: function (data) {  
  18.                 console.log (data);  
  19.                 alert("error " + data)  
  20.             }  
  21. })   

In the code given above, we are using a data template with an id “empTemplate” and a table template with an id “tbDetails”. Now, we will create the Data template and table Template, which are given below.

Here is the main code to create the Data template. 

  1. <script id="empTemplate" type="text/x-jQuery-tmpl">  
  2.     <tr>  
  3.         <td>${EmployeeId}</td>  
  4.          <td>${EmployeeName}</td>  
  5.          <td>${EmployeeDepartment}</td>  
  6.     </tr>    
  7. </script>   

Here is the main code to create the Table template

  1. <table id="tbDetails" cellpadding="0" cellspacing="0" >  
  2.     <thead style="background-color:#DC5807; color:White; font-weight:bold">    
  3.         <th>Employee Id</th>  
  4.         <th>Employee Name</th>  
  5.          <th>Employee Department</th>    
  6.          <tr style="border:solid 1px #000000">  
  7.         </tr>  
  8.     </thead>  
  9.     <tbody>  
  10.     </tbody>  
  11. </table>  

Now, we will create a container(div) to bind the Data template and Table template

  1. <div id="empContainer"></div>  

Now, we are applying styles for the table element with the code given below.

  1. <style type="text/css">  
  2. table,th,td   
  3. {   
  4. border:1px solid black;  
  5.  border-collapse:collapse;  
  6.  }  
  7. </style>   
Ebook Download
View all
Learn
View all