How to set flask url_for in JQuery
flask, jinja2, jquery, url-routing
Solution
Here goes with an example, I never really considered needing `url_for` to be accessed from the user-interface, but it's good to know how. When you click on a button, it'll use the `id` as the key to the `url_for` and show the resulting URL in an alert box.
requirements.txt
flask
git://github.com/dantezhu/flask_util_js.git
Then install them, `pip install -r requirements.txt` into your virtualenv.
app.py
from flask import Flask, render_template
from flask_util_js import FlaskUtilJs
app = Flask(__name__)
fujs = FlaskUtilJs(app)
@app.context_processor
def inject_fujs():
return dict(fujs=fujs)
@app.route('/')
def home():
return render_template('example.html')
@app.route('/foo/<something>/')
def something(something):
return 'Alright then {}'.format(something)
if __name__ == '__main__':
app.run(debug=True)
example.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
{{ fujs.js }}
<script>
$( document ).ready(function(){
$("button").on("click", function() {
var $button = $( this );
var url = flask_util.url_for('something', {something: $button.attr('id') });
alert(url);
});
});
</script>
</head>
<body>
<button id="button_a">First!</button>
<button id="button_b">Second!</button>
<button id="button_c">Third!</button>
</body>
</html>
Problem
Setting `url_for()`'s in a Jinja2 template is pretty straightforward (as long as it's in the HTML). I've been trying to set it from inside JQuery like so: ``` <script> function my_func(key) { var newHref = sprintf("{{url_for('fig', selector='%s')}}", key); $('#my_id').attr('href', newHref); } <script> ``` Where `sprintf` is just a standard string formatting function for JQuery. Nothing happens now. I also tried it with an `onClick` function instead of an `href`. It looked like this: ``` function my_Clicked(key) { $.ajax({ type: 'GET', url: sprintf("{{ url_for('fig', selector = '%s')}}", key) }); } ``` Again, nothing happens when the `<button>` is clicked. Is this even possible? The Jinja2/Flask markers `{{ }}` only seem to appear in the HTML and a processed when the page is loaded. However, I don't see why it isn't possible that you set a dynamic URL after the page has loaded, so that when you click it, the request is just sent back to the server. EDIT After using the extension suggested by odai alghamdi, I have reached a perplexing problem. I am going with an `onClick` AJAX call for the `<button>`. It now looks like this: ``` function cropzoneClicked(key) { $.ajax({ type: 'GET', url: flask_util.url_for('fig', {selector:key}) }); } ``` However, nothing happens when the button is clicked. I know that the function is being called because I can stick an alert in there. But, nothing is being rendered and the `'GET'` request isn't returning a successful callback