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
- <!DOCTYPE html>
- <html>
- <head>
- <title>News Updates</title>
- <style>
- .thNews {
- background-color: #444;
- color: white;
- }
- .thNews, .tdNews {
- border: 1px solid #444;
- padding: 15px;
- text-align: left;
- }
- </style>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
- </head>
- <body>
- <script type="text/javascript">
- $(function() {
- var params = {
- "Key": "<Parameter value";
-
- };
-
- $.ajax({
- url: "<Web API URL>" + $.param(params),
- type: "GET",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- cache: false,
- })
- .done(function(data) {
-
- var trHTML = '';
- $.each(data.News, function (i, item) {
- if (data.News[i].State != null){
- 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>';
- }
- });
- $('#divIncidents').append(trHTML);
- })
- .fail(function() {
- $('#divErr').append("error");
- });
- });
- </script>
- <div><strong><span>News Updates</span></strong>
- <table id="divIncidents">
- <tr class="trNews">
- <th class="thNews">State</th>
- <th class="thNews">Header</th>
- <th class="thNews">News Description</th>
- </tr>
- </table>
- </div>
- <div id="divErr"></div>
- </body>
- </html>
Final Output