Ajax works reading JSON datasource from file, but not from variable (Django)

Ajax works reading JSON datasource from file, but not from variable (Django)

termistermis Posts: 5Questions: 2Answers: 1

I really hope someone will help with the problem I've been stuck. I have a below code in my index.html:

$(document).ready(function() {
    $('#mydata').DataTable( {

          "ajax": {
            "url": '{% static "myapp/supplier.json" %}',  //<= works
{#                    "url": '{{ suppliers_all }}',#}             //<=does not work
            "dataSrc": ""
          },
            "columns": [
                { "data": "name" },
                { "data": "classification" },
            ]
    } );
} );

If I have source to "supplier.json" file it works like a charm, but if I try to pass django variable which gives exactly same out, it does not work.

Here's the "views.py":

def index(request):
    suppliers_all = Supplier.objects.all().values('name', 'classification')
    suppliers_all = json.dumps(list(suppliers_all))
    context = {'suppliers_all': suppliers_all,
               }
    return render(request, 'myapp/index.html', context)

Here is JSON output"

[{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]

Any ideas?

thanks

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,352Questions: 26Answers: 4,955
    edited December 2016

    Not sure about the code but I think the JSON should look like this:
    {data: [{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]}

    Kevin

  • termistermis Posts: 5Questions: 2Answers: 1

    It's still a valid JSON, but even if I hardcode JSON output from this site, I still get the same error

  • kthorngrenkthorngren Posts: 21,352Questions: 26Answers: 4,955
    edited December 2016

    What is the error you get?

    I'm not familiar with Django but I use a Python with Cherrypy backend for my project. It looks like you are having Django load the page with the data set ready to display. My procedure is different. Cherrypy loads the page (index), the client then sends the AJAX request to ```get_data`` which is a Python function get the data and return the JSON object.

    Here is an example of my Python/Cherrypy code.

        @cherrypy.expose
        def index(self):
            with open('public/html/index.html') as f:
                form = f.read()
            return form
    

    The above function returns the web page which includes the following Datatable:

    $(document).ready(function() {
    
        var table = $('#edit-table').DataTable( {
            ajax: '/get_data',
            columns: [
                { data: 'pkid' },
                { data: 'name' },
            ],
    

    The get_data (edited for brevity) function performs the SQL query and returns a JSON object data that has an array of objects containing the data:

        @cherrypy.expose
        def get_data(self, *args, **kwargs):
            result = sql_conn.sql_get_all(sql)
            json_data = json.dumps({'data': result})
            return json_data
    

    result is a dictionary list of returned items from the SQL query. The returned JSON object looks like this:
    {data: [{pkid: 1, name: "name1}, {pkid: 2, name: "name2"}]}

    You can look at this example to see the required structure of the JSON object:
    https://datatables.net/examples/data_sources/ajax.html

    Kevin

  • termistermis Posts: 5Questions: 2Answers: 1
    Answer ✓

    I finally understood what was wrong. Issue was that Django auto escaped single commas in JSON string so I couldn't parse it. I solved the following way by stringifying JSON and adding "| safe":

            $(document).ready(function() {
            var json=JSON.stringify({{ suppliers_all | safe }});
                $('#mydata').DataTable( {
                      "data": JSON.parse(json),
    
  • allanallan Posts: 63,550Questions: 1Answers: 10,476 Site admin

    Nice one - thanks for posting back!

    Allan

This discussion has been closed.