Redraw table - Server side - Json Response

Redraw table - Server side - Json Response

goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0

Hello everyone,

When I press search_date button, I get the min input value and perform an action in views.py. I want to display the rows that are smaller than the min value (datatables). I can see the rows which are smaller than min I sent with JsonResponse by printing json.x, but I don’t know how to display them by using draw() or any other way. Is it possible to do such thing while using server-side processing? Thank you in advance. (I'm using Django framework)

views.py

@csrf_exempt
def dateRange(request):
    if request.method == "POST":
        min = request.POST.get('min')

        x = list(Samples.objects.filter(patientid__lt=min).values())

        return JsonResponse({'min': min, 'x': x})

js

$('#search_date').click(function () {
          var min = $("#min").val();
          $.ajax({
            type: 'POST',
            url: '/dateRange',
            data: {'min': min, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()},
          })
          .done(function(json){
            console.log(json.x);
          });
  });

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin

    Assuming you have a reference to the DataTable you want to display them in, then use the clear() and then rows.add() methods:

    table
      .clear()
      .rows.add(json.x)
      .draw();
    

    If you need more assistance than that, please link to a test case showing the issue so we can see the JSON response and table configuration.

    Allan

  • goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0

    Hi Allan,

    Thank you for the response. I cannot share it because I work on the localhost and it is a bit huge project. But I can share table config here.

    $(document).ready(function() {
    
              table = $('#records').DataTable({
                  'serverSide': true,
                  'ajax': { url: '/api/base/?format=datatables'},
                  'columns': [
                      {'data': 'p_id_s'},
                      {'data': 'patientid.patientid'},
                      {'data': 'reception_date'},
                      {'data': 'hospital_date'},
                      ..............
                  'pagingType': "full_numbers",
                  'paging': true,
                  'pageLength': 10,
                  'lengthMenu': [5, 10, 25, 50, 100, 500, 1000, 5000, 10000, 20000],
                  'lengthChange': true,
                  'autoWidth': false,
                  'seaching': true,
                  'bInfo': true,
                  'bSort': true,
                  'orderClasses': false,
                  'order': [[ 0, "asc" ]],
                  'orderCellsTop': true,
    

    I updated js code in ready funtion, but nothing changed on the screen. Still show the whole table, not filtered one.

    $('#search_date').click(function () {
              var min = $("#min").val();
              $.ajax({
                type: 'POST',
                url: '/dateRange',
                data: {'min': min, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()},
              })
              .done(function(json){
                myDataTable = $("#records").DataTable();
                myDataTable.clear();
                myDataTable.rows.add(json.x);
                myDataTable.draw();
              });
            });
    

    JSON response(json.x) is like that (I printed it on console):

    I typed min:3 as input and there are 2 rows less than that. JSON returns the correct result but there may be a format problem.

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    APIs like clear() and rows.add() are for client side processing. These won't work with server side processing. The myDataTable.draw(); in line 13 will fetch the rows from the server using server side processing.

    To use the above you will need to disable server side processing.

    Otherwise, as discussed in your other thread, with server side processing enabled you will need to incorporate the date ranges into the data query used to fetch the row data.

    Another option might be to initialize a second empty Datatable to show the date ranges. Hide this table then when the date range search is selected hide the original table and show the date range table. Toggle back and forth as needed. Or show both on the page.

    Kevin

  • goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0
    edited September 2023

    Thank you Kevin. I get it now. I have one more question. It's actually related to this topic. Maybe I found another way to fix my problem.

    In js code, I loop through the JSON data and I wanna retrieve desired rows from that JSON.

    My question is that is it possible to seach more than one rows? ( Maybe search([ARRAY]) or search(min<x<max) )

    For example, if I wanna search a value in the first column, I am able to draw that row.

    dtable.column(1).search().draw();
    
  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    Sorry I don't understand the question or what you are trying to achieve, so these answers might not help.

    If you are using client side processing you can create a search plugin to perform more complex searches. Possibly you can find one that fits your needs here.

    You can get the JSON fetched by Datatables by using ajax.json() and loop through it using your favorite Javascript loop.

    You can use filter() to get data from a Datatable matching certain criteria to store in a Javascript variable for later processing.

    If this doesn't help then please provide more details of what you are trying to achieve.

    Kevin

  • goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0

    Sorry, I could not explain myself.

    There are over 4000 data that I display on the screen. I can iterate the JSON containing this data with the for loop. There are two fields in the upper corner of the screen where input (min and max) can be entered. After entering the min and max value, when I click on the button next to them; I want to filter column(1) values. In short, after clicking the button, I want rows with values between the min and max range to display on the screen.

    That is, I keep the rows between the min and max range in an array. Is it possible to display the JSON data in this array on the screen with column(1).search().draw()?

  • goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0

    For example, here comment (1) is not working.

    https://live.datatables.net/kuwomihe/1/edit

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    If you are going to return 4000 rows of JSON data to the client then turn off server side processing and let Datatables display all the rows via the ajax option. Use the Date Range search plugin to filter the data based on the date range. Similar to this age range example.

    Kevin

  • goktuginal41@gmail.comgoktuginal41@gmail.com Posts: 57Questions: 22Answers: 0

    The amount of data increases, unfortunately, if I do client side processing, it takes 20 seconds to load the page.

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    Maybe I misunderstood. I thought you wanted to return a JSON response with 4000 rows and loop through them to find the rows within the date range to populate the Datatable. Is my understanding incorrect?

    Kevin

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949
    Answer ✓

    Do you want the initial table populated with row data? If not then initialize an empty Datatable, ie no ajax or data option. When the user selects the date range use jQuery ajax(), like above to fetch the rows in the date range and clear() and rows.add() the response to the Datatable. Also remove the server side processing option.

    Kevin

Sign In or Register to comment.