0

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

1 Answer 1

3

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(); 
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this seems to be what I needed
@adnan, there was error in the code which is corrected.
A slightly more flexible and efficient approach to the above (assuming you may well need thse values for the initial request as well) would be to put the getDataTableUrl() function call into the data table initialisation e.g. ajax : { url : getDataTableUrl() } and then call table.ajax.reload() wherever you need to reload

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.