I want to use an AJAX call with parameters within a Jinja2 template. But how do I make it possible? I want to do something like this.
JavaScript:
$.get("test.html", { name: "John", time: "2pm" } );
jinja template:
<div>
{{name}} {{time}}
</div>
You need to access the request object on the server side to get the arguments. I'm assuming you're using Flask, but if not, the basic idea should be the same on other web frameworks as well. Let's say you have a simple little index.html, where you use Javascript to make your Ajax query:
$.get("{{ url_for('ajax') }}", {name: "John", time: "2pm"});
Note that if you're not using Jinja2 to render the script portion, replace the url_for()-call with the actual URL, so something like /ajax in my example further below:
$.get("/ajax", {name: "John", time: "2pm"});
Now, on the server side you would have something like this:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/ajax')
def ajax():
#Access arguments via request.args
name = request.args.get('name')
time = request.args.get('time')
#NOTE: In real code, check that the arguments exist
#Silly logging call to show that arguments are there
app.logger.info(name)
app.logger.info(time)
#Do stuff here to do what you want or modify name/time
...
#Render template and pass the arguments to it
return render_template('ajax.html',
name=name,
time=time)
@app.route('/index')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
and ajax.html would look something like this for example:
<h2>{{ name }}</h2>
<h2>{{ time }}</h2>
So request.args is where you can access the arguments you've passed with GET, but you need to pass them explicitly to Jinja2 with the render_template() call. Jinja2 is just a templating language and it is not aware of your arguments (1) unless you pass them to it.
1) With some exceptions. Flask for example does pass a few arguments to Jinja2 implicitly, like the request object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With