I have a column in my jQuery datatable that renders a green checkmark link if data == true or a red X if data == false:
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '@Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '<a href=\"' + paymentSet + '\" class="fas fa-solid fa-check" style="color: green"></a>';
}
return '<a href=\"' + paymentSet + '\" class="fas fa-solid fa-times" style="color: red"></a>';
}
},
The problem is that when I click one of the links (either green checkmark or red X), it navigates to another page. I know that this is because I am using href and Url.Action.
When a user clicks one of the links, I want to call the /Payment/Set method to update the data (green checkmark to red X and vice versa) and then I want to redraw my datatable (i.e. dataTable.draw()) without navigating from the current page (i.e. Index view). /Payment/Set method updates the data without returning anything (i.e. void).
Update: I tried the following and it almost works, meaning that when I click one of the links, the data is updated and the datatable is refreshed, except it still tries to navigate to another page.
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '@Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '<a href=\"' + paymentSet + '\" onclick="return onclickFunction()" class="fas fa-solid fa-check" style="color: green"></a>';
}
return '<a href=\"' + paymentSet + '\" onclick="return onclickFunction()" class="fas fa-solid fa-times" style="color: red"></a>';
}
},
<script>
function onclickFunction() {
$.ajax({
type: "GET",
url: $(this).attr("href"),
success: function () {
paymentDataTable.ajax.reload();
}
});
}
</script>
If you use an anchor
<a>it is obvious that the browser will navigate to another page. That's the actual purpose of the anchor tag.You should use an AJAX function to call when your button is pressed and at the callback call the reload of the table.
This can be a way:
Then you should create two more functions, one with the AJAX call and one with the table reload to be called as callback.
Then in the reloadTable function just call the ajax.reload() method of the DataTable api.
for example
Here is the documentation of DataTables reload method.
Here is the documentation of JQuery AJAX.
You may have to adapt the example code to your specific backend purpose.