i'm a new dev , I've a Json object with data and i'm trying to pass it to a certain page using render_template
I've seen couple of answers about this but for some reason none of them have worked for me
i know the connection between Javascript and Flask is solid as i can console.log("string") at Onload function in JS but it doesn't seem to recognise anything i pass with the render template
things i have tried so far
saving json object as variable and pass it with the render template.
x = {"Success": True , "Msg":" lets try to get jinja to work - email {{ current_user.email }} " , "displayname":current_user.name}
t = "test"
return render_template("index.html", x=x ,t=t)
on JS
document.addEventListener('DOMContentLoaded' , function () {
console.log("loaded");
const onStay = new XMLHttpRequest();
onStay.open('post' , "stay" , true);
onStay.send(null);
onStay.onload = ()=>{
console.log("i got response from flask ... onstay.onload , cheers !");
//console.log(x);
var rt = t;
console.log(rt);
var resStay = JSON.parse(x.responseText);
var tt = JSON.parse('{{ x | tojson | safe}}');
so i'm also testing if i can pass jinja2 code or flask_login code actually save it in a variable of some sort and respond to it with JS
the second attempt was trying to jsonify method and parse it
on python :
X = jsonify({"Success": True , "Msg":" lets try to get jinja to work -
email {{ current_user.email }} " , "displayname":current_user.name})
return render_template("index.html", X=X)
on JS end :
onStay.onload = ()=>{
var res = JSON.parse(reqSignup.responseText);
console.log("res === " , "\n" , res );
the output i get is
JavaScript.js:11 i got response from flask ... onstay.onload , cheers !
JavaScript.js:13 Uncaught ReferenceError: t is not defined
at XMLHttpRequest.onStay.onload (JavaScript.js:13)
onStay.onload @ JavaScript.js:13
load (async)
JavaScript.js:191 [email protected]
qwe
JavaScript.js:313 DATA = FormData {}
The problem is that you are trying to access variables directly from JavaScript. What you need to do is to use these variables in the Flask Template using Jinja and in it, put a call to your JavaScript.
A classic example is putting a button, with an onclick=YourFunction(x). When calling the function it will pass the value it has in the variable.
You should be using the default Flask template engine which is Jinja, but if you prefer a template engine I developed to facilitate this kind of thing, if Sucuri.
Hope this helps.