jsonify'ed Data From Flask Cant Be Seen on Data Tables - Server Side

jsonify'ed Data From Flask Cant Be Seen on Data Tables - Server Side

Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0
edited July 2019 in Free community support

Hi, I used this class to get my mongodb table to datatables: https://github.com/Sighery/mongodb-flask-datatables

And here's my code dervied from it:

# Method the DataTables client plugin will call
@app.route('/example_datatables', methods = ['GET','POST'])
def example_datatables():
    # Set the name for the column, and it's mapping on the database
    columns = [
    ("unique_id",['unique_id']),
    ("cty_row_id",'cty_row_id'),
    ("OBJECTID",'OBJECTID'),
    ("parcel_id",['parcel_id'])]

    filter_columns = [  

    ]



    example_index = [
        (0, DataTablesServer.DESC)
    ]



    def custom_filtering_function(request_values, columns, filter_columns):
        filtering_data = {}

        for index, column in enumerate(columns):
            # Check if the column is searchable both client side and
            # server side
            valid_search_columns = [x['column'] for x in filter_columns]

            searchable = parse_bool(request_values['columns[{}][searchable]'.format(index)])
            search_value = request_values['columns[{}][search][value]'.format(index)]

            if searchable is True and search_value != '' and index in valid_search_columns:
                # From the corresponding column, get its mapping, an
                # example might be sensors.0.reading
                search_in = '.'.join(str(x) for x in column[1])

                # Save the mapping along the options for the filtering
                # of that column
                filtering_data[search_in] = {
                    '$regex': re.compile(
                        re.escape(search_value),
                        re.IGNORECASE
                    )
                }


        if not filtering_data:
            return None

        return filtering_data




    table = DataTablesServer(
        request = request,
        columns = columns,
        index = '_id',
        filter_columns = filter_columns,
        db_name = "fruition",
        collection = "reisearch",
        custom_filtering_function = None,
        mongo_host = 'localhost',
        mongo_port = 27017
    )




    data = table.output_result()
    print(json.dumps(data))
    return jsonify(data)

I have proven that with the library/script provided I was able to get my data - http://prntscr.com/ojkc64 but for some reason it isn't displaying on my datatable(http://prntscr.com/ojkdb2) here is the code my table, JS and Ajax

        <table id="example" class="display" style="width:100%">
         <thead>
         <tr>


        <th>unique_id</th>
        <th>cty_row_id</th>
        <th>OBJECTID</th>
        <th>parcel_id</th>


        </tr>
        </thead>

        </table>

        <script type="text/javascript">

         $(document).ready(function() {
            var table =  $('#example').DataTable( {



                'searching': true,
                'lengthChange': true,
                'serverSide': true,
                'iDisplayLength': 200,
                'order': [[1, 'desc'], [2, 'asc']],
                'ajax': '/example_datatables',
                'lengthMenu': [10, 25, 50, 100, 150, 200, 250, 300, 400, 500],
                "paging":   true,
                "ordering": true,
                "info":     true,
                dom: 'Bfrtip',

                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    'csvHtml5',
                    'pdfHtml5',
                    'print'
                ]


            } );

                  // Reload table every 30 seconds
              setInterval(function() {
                table.ajax.reload(function() {}, false);
              }, 30000);



            $('#example tbody').on( 'click', 'tr', function () {
                if ( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected');
                }
                else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
            } );

            $('#button').click( function () {
                table.row('.selected').remove().draw( false );
            } );

            // Setup - add a text input to each footer cell
            $('#example thead th').each( function () {
                var title = $(this).text();
                $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
            } );


            // Apply the search
            table.columns().every( function () {
                var that = this;

                $( 'input', this.header() ).on( 'keyup change', function () {
                    if ( that.search() !== this.value ) {
                        that
                            .search( this.value )
                            .draw();
                    }
                } );
            } );



        } );


        function codename() {

        if(document.formname.checkboxname.checked)
        {
        document.formname.textname.disabled=false;
        }

        else
        {
        document.formname.textname.disabled=true;
        }
        }

        </script>            

I tried fiddlin with the ajax parameter on this forum I found some guides but I just cant display them, I thought that there might be some contraditictions on the parameters I am having, which is why I am asking here, since I have lots of DataTable-related stuff in my JS

Answers

  • kthorngrenkthorngren Posts: 21,150Questions: 26Answers: 4,919

    Its hard to tell from the screenshots and code snippets what is happening. The JSON screenshot doesn't have enough information to understand the JSON datat structure. I can see it is an array of arrays. But I can't tell if is in a data object as expected by default:
    https://datatables.net/manual/ajax

    I would start by looking at the actual response in the browser's developer tools. The screenshot looks like output from Flask.

    Do you get any errors in the browser's console?

    I would temporarily remove lines 47 - 87 until you get the table initially populated. Just to make sure that code isn't affecting anything with the table.

    Please post a snippet of the JSON response in the developer tools > network > Response tab. Just so there is no confusion post from the start of the response to include the first two or three rows. Then grab the last two or three rows all the way to the end.

    I see that your screenshot has six columns but your code above has four. Thats a it confusing to understand what you really have.

    Kevin

  • Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0

    Thank you very much for your reply.

    I'm gettting like: DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

    On my browsers console, I'm not getting any DataTable-like Errors, but some CSS Stuff.http://prntscr.com/ojlmgn http://prntscr.com/ojlnuu

    About the mismatch of tables - I have lots of columns so I just shortened them to four in order to ask this question.

    Upon reading the Ajax reference I think I'm doing something similar to 'Array of data' as what I am returning is an array of arrays - which is what you have seen in my screenshot

  • Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0

    The data that I am returning lloks like this:

    {"draw":"1", "recordsFiltered": 441348, "recordsTotal": 441348, "data": [ [ ], [ ],..., [ ] ] }

  • kthorngrenkthorngren Posts: 21,150Questions: 26Answers: 4,919

    Did you follow the steps listed at the link in the error?
    http://datatables.net/tn/1

    What you post above looks correct but Datatables doesn't like it. Since you are using Server Side Processing you should get only 200 rows of data ('iDisplayLength': 200, or change this to something smaller) to paste into https://jsonlint.com/ .

    Optionally you could use the debugger and post the ID for the developers to take a look.

    Kevin

  • Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0

    I see, that was very informative, now I got this error when I followed the instructions:

    SyntaxError: JSON.parse: unexpected character at line 1 column 190 of the JSON data

    What does this mean?

    and here's the data when I pasted into lint: http://prntscr.com/ojm1yd

  • Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0

    I think its valid Json. I'm running out of clues whats going wrong with the population

  • Firiyuu77Firiyuu77 Posts: 6Questions: 1Answers: 0

    I think I figured out whats wrong

    Error: Parse error on line 3:
    ...IA, TX 77354-2124", NaN, NaN, "t", NaN, 
    -----------------------^
    Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
    

    It's not accepting NaN

  • kthorngrenkthorngren Posts: 21,150Questions: 26Answers: 4,919
    edited July 2019

    That sounds right. Your server script will need to do something with the NaN data to allow the response to be a valid JSON. What that is will depend on your requirements.

    Kevin

This discussion has been closed.