1

I am really new to Flask, and I have encountered this issue while I was trying to pass data from Python Flask to JS in the front end:

app.py

@app.route("/",methods=['POST', 'GET'])    
def search():
    data = {"username": "test", "site": "stackoverflow.com"}
    return render_template('search.html',data=data)

search.html

<html>
    <head>
    <script type="text/javascript" src="{{url_for('static', filename='js/search.js')}}"></script>
    </head>
    <body>
    </body>
</html>

search.js

console.log(data) 

and the result I got from the console was

ReferenceError: data is not defined

I have checked out this question, and that one still can't address the issue in this case, I tried. What is the main issue here? Is it a syntax issue? Or data formatting issue?

Eric Cai
  • 83
  • 2
  • 8
  • In response to 'What is the main issue here?' - Your `data` variable is a python/jinja variable, not a JS variable, which is why JS is returning 'not defined'. What is a possible solution? An AJAX call to get the data, or something like `var data = {{ data }}` (in your JS), which might require further JS parsing. – PGHE May 05 '20 at 02:04

1 Answers1

0

In your html you should use your data doing a cast to json, as explained by @PGHE.

To be able to use your data with minimal changes in your code, you should change your search.html to:

<html>
  <head>
  <script>
    const jsondata = JSON.parse('{{ data | tojson | safe}}');
    console.log(jsondata) //should show your data
  </script>
  </head>
  <body>
  </body>
</html>

Here it is a inline javascript inside html, but you can do it inside your file

Danizavtz
  • 3,166
  • 4
  • 24
  • 25
  • Thanks for your answer! Yes, it worked in the HTML script tag!! Sorry just outta curiosity, why when I moved the script to the JS file, I got the error message: `SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data`? shouldn't these two be equivalent? – Eric Cai May 05 '20 at 15:52
  • Never worked with a config like that, but maybe a workaroud could be serve your data as a route returning a json (in flask use `from flask import jsonify`, `@app.route` `def jsondata():` `return jsonify(data)`, and after that in your javascript you could use some request/response lib to fetch the data from your route. – Danizavtz May 05 '20 at 20:21