I want to consume ajax returned data in my JQuery DataTables. I have created loop to view every row and also need to add a view button for them. I pass all data to JQuery DataTables. I cannot understand how to do that.
This is my ajax
request
<script>
$(document).ready(function () {
$("#searchArea").show();
var uID = $("#userName").val();
var tableProduct = $('#dataTbl').DataTable({
"bSort": false
, "oLanguage": {"sZeroRecords": "", "sEmptyTable": ""}
});
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath}/restservice/viewApplication/' + uID,
success: function (result) {
var jString = JSON.stringify(result);
var jdata = JSON.parse(jString);
for (var x = 0; x < jdata.length; x++) {
var td1 = jdata[x].snumber;
var td2 = jdata[x].date;
var td3 = jdata[x].slsNo + " in " + jdata[x].slsiUnit;
var td4 = jdata[x].productDesc;
var td5 = jdata[x].status;
var td6 = "view btn1";
var td7 = "view btn2";
var td8 = "view btn3";
tableProduct.row.add([td1, td2, td3, td4, td5, td6, td7, td8]).draw(true);
}
}
});
});
</script>
I want to add this code for every row. How can I do that ?
<form method="post" action="${pageContext.request.contextPath}/viewApplication" target="_blank">
<input type="hidden" name="snumber" value="jdata[x].snumber"/>
<input type="submit" class="btn btn-primary btn-block" value="View" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
Consuming Ajax data in DataTables
There is already a handy feature in DataTables to fetch data from ajax and consume them as you configure your table. Just use the
ajax
option and tell about the data source you want to consumeSee this documentation for complete guideline.
Note: here passing
dataSrc
option as empty tells dataTable to expect an array rather than objects from ajax responseFollowing is a example that depicts a senario where datatable is configured to consume a api response. For demonastration purpose I used a public dummy api service that returned an json array. See this dummy api response.
Having Custom button or form in row
In your datatable you can configure each column rendering logic. Like the case you are dealing, you want separate columns of button behave as form submission. You should tell this in
columnDefs
option as passing an array of definations.In the code snippet above I also showed how you can achive that. In that example I added 3rd column (
target: 2
) by defining its rendering logic. Inrender
callback you can returnhtml
that should be placed in that column. I only added<button>view</button>
but as you see you can return any html like forms with input fields and buttons and whats not.render
option takes a function that is provided withdata, type, row
parameters. Hence you can exploit these data for rendering your column html or any logic you what. Thats a lot of flexibility, isn't it ?You will find a complementary guildline from this columnDefs documentation.