Dynamic HTML Table or Grid from JSON using JQuery in SharePoint

In this blog we are going to see how the HTML table can be created dynamically and populating the values from the return JSON value by calling Web API using JQuery.
 
Step 1
 
Edit the SharePoint WebPart page as shown below.
 
 
 
Click the link Add WebPart
 
 
Select Insert WebPart from the top ribbon.
 
 
Select the "Media and Content" category and find "Script Editor" from the top ribbon.
 
 
Step 2
 
After adding the "Script Editor" WebPart.
 
 
Click on the "EDIT SNIPPET" to type in the codes and click "Insert" to see how the codes are reflected in the page.
 
 
Below sample code can be used to fetch data from any WebAPI and to get the Return JSON for the creation of dynamic table.
 
Note: Please take care of the yellow highlighted parts. Those are all sample variables, it has to changed according to the your JSON response object.
 
Code
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title>News Updates</title>  
  5. <style>  
  6. .thNews {  
  7. background-color: #444;  
  8. color: white;  
  9. }  
  10. .thNews, .tdNews {  
  11. border: 1px solid #444;  
  12. padding: 15px;  
  13. text-align: left;  
  14. }  
  15. </style>  
  16. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>  
  17. </head>  
  18. <body>  
  19. <script type="text/javascript">  
  20. $(function() {  
  21. var params = {  
  22. "Key""<Parameter value";  
  23. // Request parameters  
  24. };  
  25. // provide the Web Api url (must) and include the Params (parameters) if it is required.  
  26. $.ajax({  
  27. url: "<Web API URL>" + $.param(params),  
  28. type: "GET",  
  29. contentType: "application/json; charset=utf-8",  
  30. dataType: "json",  
  31. cache: false,  
  32. })  
  33. .done(function(data) {  
  34. //alert("success");  
  35. var trHTML = '';  
  36. $.each(data.News, function (i, item) {  
  37. if (data.News[i].State != null){  
  38. trHTML += '<tr class="trNews"><td class="tdNews">' + data.News[i].State + '</td><td class="tdNews">' + data.News[i].Header + '</td><td class="tdNews">' + data.News[i].NewsDesc + '</td></tr>';  
  39. }  
  40. });  
  41. $('#divIncidents').append(trHTML);//To add the table row to table  
  42. })  
  43. .fail(function() {  
  44. $('#divErr').append("error");// To display the error in div  
  45. });  
  46. });  
  47. </script>  
  48. <div><strong><span>News Updates</span></strong>  
  49. <table id="divIncidents">  
  50. <tr class="trNews">  
  51. <th class="thNews">State</th>  
  52. <th class="thNews">Header</th>  
  53. <th class="thNews">News Description</th>  
  54. </tr>  
  55. </table>  
  56. </div>  
  57. <div id="divErr"></div>  
  58. </body>  
  59. </html>  
Final Output
 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now