datatables.net fail: "Uncaught SyntaxError: Unexpected token &"

642 views
Skip to first unread message

Tom Campbell

unread,
Dec 26, 2015, 7:08:12 PM12/26/15
to web...@googlegroups.com
Trying to display rows using the datatables.net DataTable() function by converting query results to JSON, but getting error "Uncaught SyntaxError: Unexpected token &". Though the raw data displays correctly in the view below, when I look at the results in the web console debugger I see that the generated program seems to show the JSON converted back to XML:

<!-- Debugger shows this: -->
$(document).ready(function(){
    $("#person-table").DataTable({
        "aaData":  [{&quot;first_name&quot;: &quot;Super&quot;, &quot;last_name&quot;: &quot;Man&quot;, &quot;id&quot;: 1}, {&quot;first_name&quot;: &quot;Massimo&quot;, &quot;last_name&quot;: &quot;Di Pierro&quot;, &quot;id&quot;: 2}])                                  
    })
});

in model db.py:
db.define_table('person',Field('last_name'), Field('first_name'))
db.person.update_or_insert(last_name='Man',first_name='Super')
db.person.update_or_insert(last_name='Di Pierro',first_name='Massimo')

in controller default.py:
def index():
    import json
    people = json.dumps(db(db.person).select().as_list())
    return dict(results=people)

In view index.html:
   <table id="person-table" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>First name</th>
                <th>Last name</th>
            </tr>
        </thead>
    </table>
 ...
    <h1>Raw data</h1>
    <code>
     results: {{=results}}
    </code>

<script type="text/javascript">
$(document).ready(function(){
    $("#person-table").DataTable({
        "aaData":  {{=results}}                                 
    })
});
</script>

The view prints out an empty Datatable, followed by correctly formed JSON in the "Raw Data" portion:

  ID First name Last name

  Raw data
  results: [{"first_name": "Super", "last_name": "Man", "id": 1}, {"first_name": "Massimo", "last_name": "Di Pierro", "id": 2}]



Tom Campbell

unread,
Dec 26, 2015, 7:44:09 PM12/26/15
to web2py-users
After a day of messing this, of course I answered it myself moments after posting!

Answer was to define columns used and to use {{=XML}} helper:a


<script type="text/javascript">
$(document).ready(function(){
    $("#person-table").DataTable({
        "data":  {{=XML(results)}},                
        columns: [
            { data: 'first_name' },
            { data: 'last_name' },
            { data: 'id' }
        ]
    })
});
</script>

Tom Campbell

unread,
Dec 27, 2015, 12:32:29 AM12/27/15
to web2py-users
Cleaner versions in tutorial style at pyguy and and web2pyslices. Criticism warmly welcomed.
Reply all
Reply to author
Forward
0 new messages