adnan adnan - 4 months ago 27
Javascript Question

jQuery Datatable - changing data url

Currently using the jQuery Datatables plugin.

I now need to be able to change the ajax data source based on some form input values, which would be submitted on a button click?

What is the recommended method for achieving this?

$(document).ready(function () {

$('#btnReport')
.click(function () {
var table = $('#reports').DataTable();
table.ajax.reload();
});

var querystring = '?from=' + $('#datetimepickerFrom').val() + '&till=' $('#datetimepickerFrom').val();

var url = '/api/reports/custom';

var table = $("#reports").DataTable({
ajax: {
url: url + queryString,
dataSrc : ""
},
columns: [
{
data: "fullName"
},
{
data: "timeIn"
}
]
});

});


Many thanks

Answer

Use ajax.url() and ajax.url().load() to set URL for the table and load data from that URL.

For example:

function getDataTableUrl(){
    return 
        '?from=' + $('#datetimepickerFrom').val() 
        + '&till=' +  $('#datetimepickerFrom').val();
}

$('#btnReport')
    .click(function () {
        var table = $('#reports').DataTable();
        table.ajax.url(getDataTableUrl()).load(); 
    });
Comments