1

Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin.

I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading).

I want to retrieve data from the following URL:

/api/device_input/?format=datatables&device_id=something
// device_id can be 1, 2, 3 and so on.

The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing):

1) User enters device ID into a form. Form gets submitted.

2) Django view takes the POST request and returns the filtered queryset to the template.

3) The queryset populates the HTML table values and datatables handles the rest (pagination etc)

But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is:

1) User opens page, an empty datatable is displayed, with a prompt to enter device ID.

2) User enters device ID, and the datatable is loaded with records for that device id.

But the datatables ajax request only gets invoked when someone messes with the datatable (such as change page or select page length). I want to invoke the ajax request when someone enters device_id into my form and dynamically tell ajax to create the right URL.

Here's what my javascript looks like:

<!-- Javascript function to initialize the datatable -->
<script>
    var device_id = document.getElementById("id_input").value
    $(document).ready(function() {
        $("#device_inputs_table").DataTable({
            "lengthMenu": [
                [10, 20, 30, -1],
                [10, 20, 30, "All"]
            ],
            fixedHeader: {
                headerOffset: 62
            },
            "order": [
                [0, "desc"]
            ],

            "serverSide": true,
            "ajax": "/api/device_input/?format=datatables&device_id=" + device_id, // need to add a number at the end that user will input
            "columns": [
                // All my table columns
            ]
        });
    });
</script>

I'm sure this is simple to do, but my unfamiliarity with ajax and javascript has me scratching my head, any help is appreciated!

UPDATE: I tried adding a simple variable to get device_id from the form element, but it doesn't get added to my URL... how do I print my URL out on the dom? (I'm only checking through the network tab on chrome dev tools...) Of course my form doesn't even invoke the ajax request so that's another issue.

2 Answers 2

1

First you need to declare a variable to hold the DataTable and call it from your javascript.

Example:

var deviceInputsTable = $('#device_inputs_table').DataTable({
// Rest of the table declaration goes here.
})

Then, you create a function that triggers to load data in your deviceInputsTable, something like:

function loadDeviceInputsTableData(deviceID){
device_id = deviceID // (get this from the input)
// do the ajax call here and this is the important part:
success: function(data){
    // This is just a rough scratch, but this is how you initially call the first data in the table, consequent calls will now be server-side since your device_id now has a value in the ajax call you showed above.
    deviceInputsTable.clear().rows.add(data).draw()
}
}

I hope this helps.

EDIT, concerning your comment below:

You can use a normal jQuery ajax call. Something like this:

function loadDeviceInputsTableData(deviceID){
device_id = deviceID;
            $.ajax({
                type: 'GET',
                url: `SomeURLhereAppendingthedeviceIDParameter`,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                   // Transform the AJAX's response here and get the data to add to your data table below
                   deviceInputsTable.clear().rows.add(data).draw()
                }
            });
};

To trigger the ajax again on change of the input, you can call the on change function in jQuery.

$('#id_input').on("change",function(){
loadDeviceInputsTableData($('#id_input').val());
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks for the answer. I've assigned a variable to store my table in and added your function in. The // do the ajax call here part, how do I make the ajax call there? And how do I trigger this function when my device_id input element changes? I tried onchange and some other events and could not get it to fire...
Now that I re-read your answer I realize what you meant by "you can use a normal jquery ajax call", I was just so unfamiliar with both ajax and jquery back then that I didn't know how. Thanks for your help.
1

This issue was solved by using datatable's API, my question was about changing the ajax url dynamically upon user input. Here's what I did:

// Get device ID from wherever user inputs it, in my case it was a button with id: id_input
device_id = document.getElementById('id_input').value;

// Dynamically set your datatable's ajax URL to whatever you want. I concatenated the device id 
// string with my url string. ajax.url("your URL") is enough to set the URL
// .load() is for getting data from the new URL you've just set.

$('#device_inputs_table').DataTable().ajax.url(
            "/api/device_input/?format=datatables&device_id=" + device_id).load();

Doing this gave me the final URL: "/api/device_input/?format=datatables&device_id=1" (if user inputted 1) fixing my issue.

Comments

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.