0

my flask code section that have issue main.py

from flask import Flask, render_template, url_for
import pandas as pd 
import json

app = Flask(__name__)


@app.route('/')
def home():
    df = pd.read_csv('test.csv')
    df = df.groupby('name')['marks'].sum()
    j = df.to_json(orient='index')
    return render_template("work.html",s=j)

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

and i want to pass j into my javascript file that is look like that work.js

//pie chart
var s = {{ j|safe }};
var keys = [];
   for(var k in s) keys.push(k);
var value = [];
   for (var k in s) value.push(s[k]);

var data = [{
  values: value,
  labels: keys,
  type: 'pie'
}];

var layout = {
  height: 400,
  width: 500
};
Plotly.newPlot('myDiv1', data);

work.html

<html>
        <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <link rel="stylesheet" type="text/css" href="styles.css">
        </head>
        <body>
        <div class="navbar"><span>data representation with Plotly.js</span></div>

        <div class="wrapper">
            <div id="myDiv1"></div>
            <script type="text/javascript" src={{ url_for('static', filename='work.js')}}> 
            </script>
        </div>
        </body>
</html>

how to pass j variable in flask to s variable in javascript file that render with html page and show right content or say that no graph shown Thank you

3
  • Can you add stack trace of the error? Also, are you sure that you don't have any caching issue? Commented Mar 15, 2019 at 9:34
  • there's not much to go on here, but it appears that your s in the JS script is in fact a (JSON) string. Try s = JSON.parse(s) before the loops. Commented Mar 15, 2019 at 9:43
  • oh, and you refer to wanting to "pass j into my javascript file" - only the work.html template get the {{s|tojson}} converted to the actual value. This will work if this is in a script tag in the template though (which is what I assumed when I first read your post). Commented Mar 15, 2019 at 9:44

1 Answer 1

1

You can't do that. You have to return that json in your flask method and make an ajax request from javascript.

from flask import jsonify

@app.route('/')
def home():
    j = df.to_json(orient='index')
    return jsonify(j)

I don't know if flask has something like JsonResponse as django has. If yes you should use that like: return JsonResponse(j)

$.ajax({url: "your_url", success: function(result){
    //result is what you returned from flask
}});
Sign up to request clarification or add additional context in comments.

Comments

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.