So I have a table with the FORM element:
<table id="example" class="sortable">
<caption><h3><strong>Product inventory list</strong></h3></caption>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Amount</th>
<th>Location</th>
<th>Purchase date</th>
</tr>
</thead>
<tfoot>
<form id="myForm" action="http://wt.ops.few.vu.nl/api/xxxxxxxx" method="get">
<td>
<input type="text" name="name" required>
</td>
<td>
<input type="text" name="category" required>
</td>
<td>
<input type="number" name="amount" required>
</td>
<td>
<input type="text" name="location" required>
</td>
<td>
<input type="date" name="date" required>
</td>
<td>
<input type="submit" value="Submit">
</td>
</form>
</tfoot>
</table>
The information I fill in gets send to my API link, but now I need to append the information I fill in, directly in the table.
I know I can send an AJAX GET request, to get the information stored in the API, but how do I insert the returned JSON data into the table?
You can get the values of
<input id= "nameid" type="text" name="name" required>
with
var value = $("#nameid").val();
or set it with
$("#nameid").val("myname");
You can use jQuery ready or button click event to load data. Below code snippet is demonstrates loading of data automatically once the HTML document is loaded. Hope this answers!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Product Inventory List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<table id="products" class="sortable" border='1'>
<caption><h3><strong>Product inventory list</strong></h3></caption>
<tr>
<th>Name</th>
<th>Category</th>
<th>Amount</th>
<th>Location</th>
<th>Purchase date</th>
</tr>
</table>
<script>
var api = 'http://example.com/api/v1/products';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: api + '/products',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data.products, function (i, item) {
trHTML += '<tr><td>' + data.products[i].name + '</td><td>' + data.products[i].category + '</td><td>' + data.products[i].amount + '</td><td>' + data.products[i].location + '</td><td>' + data.products[i].pdate + '</td></tr>';
});
$('#products').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
})
</script>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.