1

I am trying to send mysql query results in the context of my Django template to a Javascript variable. I am using pivot.js https://github.com/nicolaskruchten/pivottable which requires jquery and the jquery UI.

In the Django view:

cursor.execute(query)
data = dictfetchall(cursor)
json_data = json.dumps(data, cls=DateTimeEncoder)
context['pivot_data'] = json_data

This works and I am able to see the data in the javascript console but for some reason it is not formatted properly.

From my Django template:

{% load staticfiles %}
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type='text/javascript' src="{% static "js/pivot.js" %}"></script>
<script type='text/javascript'>
    var pivotData = '{{ pivot_data }}';
    $("#output").pivotUI(
        pivotData,
        {
            rows: ["XXX"],
            cols: ["YYY"]
        }
        );
</script>

1 Answer 1

3

The following is going to be a string (it's a JSON object that you quoted):

var pivotData = '{{ pivot_data }}';

You can do:

var pivotData = {{ pivot_data }};

But this is bad practice, as it's akin to eval-ing the JSON data (and will fail certain on special characters, as documented here).

A better approach would be:

var pivotData = JSON.parse('{{ pivot_data }}');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That solved the problem. I ended up using:var pivotData = JSON.parse('{{ pivot_data|escapejs }}');
Thank you for leaving the comment @user3453012. I HAD to have the |escapejs for it to work. super helpful question and answer :)

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.