3

It now all works. If you want to load a file containing the JSON payload uncomment this line

// "url": "static/objects2.txt", // This works for a static file

and comment this one,

"url": "/index_get_data", // This now also works

flaskTest.py

from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/index')
@app.route('/')
def index():
  return render_template('index.html')

@app.route('/index_get_data')
def stuff():
  # Assume data comes from somewhere else
  data = {
    "data": [
      {
        "id": "1",
        "name": "John Q Public",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "extn": "5421"
      },
      {
        "id": "2",
        "name": "Larry Bird",
        "position": "Accountant",
        "salary": "$170,750",
        "start_date": "2011/07/25",
        "office": "Tokyo",
        "extn": "8422"
      }]
  }
  return jsonify(data)


if __name__ == '__main__':
  app.run(debug=True)

/templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Datatables Example</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css"/>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>My Heading</h1>
<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
<script>


function setupData() {
    $(document).ready(function () {
        $('#example').DataTable({
            "ajax": {
                // "url": "static/objects2.txt", // This works for a static file
                "url": "/index_get_data", // This now also works
                "dataType": "json",
                "dataSrc": "data",
                "contentType":"application/json"
            },
            "columns": [
                {"data": "name"},
                {"data": "position"},
                {"data": "office"},
                {"data": "extn"},
                {"data": "start_date"},
                {"data": "salary"}
            ]
        });
    });
}

$( window ).on( "load", setupData );
</script>
</body>
</html>
5
  • Maybe doing json.dumps() for the data. Commented Jun 19, 2018 at 16:52
  • @Divise I tried it, same result. I suspect that ajax is expecting more than just a json object. Thank you for your effort! Commented Jun 19, 2018 at 17:47
  • If you're just trying to specifically receive json data from the request you do not have to do return render_template() you can just do return jsonify(mydata) Commented Jun 19, 2018 at 18:31
  • Divise you put me on the right track. @kthorngren of the DataTables forum summed it up as "The problem is you can't return the web page and data at the same time for Datatables. You will need to return the web page, it will load and Datatables will initialize then send the ajax request. This will need to be a different URL that will simply return the JSON data. You will have two Python functions; index and dt_index (or whatever you want to call the URL for the ajax request)." I'm going to edit the question to show the solution. Thank you for your help. Commented Jun 19, 2018 at 21:31
  • No problem I'll add it as an answer for others to see Commented Jun 19, 2018 at 21:33

1 Answer 1

2

Instead of doing return render_template() just do:

return jsonfiy(my data)

You're sending data not a view so there is no need to return a template render as a response.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, did something changed in Datatable? I am trying your code and get this error : Invalid JSON response

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.