Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
[AF] Flask hyperlinks with ajax

Hi everyone, I'm making an application with flask, and I'd like to have a link on my page that send some data to the server, does some stuff with it, and then returns one or multiple hyperlinks to be displayed on the page as a result. I want to do this on the existing page, not load a different page. I figured out how to do this with Jquery/Ajax, but I'm running into errors when rendering a url pointing to an internal location. Below is an example, as simplified as I can make it.

Flask app:

from flask import Flask, url_for, render_template

app = Flask(__name__)

@app.route('/start', methods = ['GET','POST'])
def start():
return render_template('index_test.html')

@app.route('/next_page', methods = ['POST', 'GET'])
def next_page():
return render_template('next_page.html')

@app.route('/get_url', methods = ['POST', 'GET'])
def get_url():
return '<a href="{{ url_for(\'next_page\' )}}"> ajax link </a> '

if __name__ == '__main__':
app.run(debug = True)
Start page:

<html>
<head>
<script type = "text/javascript" src="{{ url_for('static', filename='jquery-2.1.1.min.js') }}"></script>
<head>
<body>
<div>
<a href="{{ url_for('next_page')}}">go to next page</a>

<a id = "link1" href="javascript:void(0)">now with ajax</a>
</div>
<div id="new_link">

</div>
<script type="text/javascript">

$("#link1").click(function(){
$.post('/get_url', function(result){
console.log(result);

$("#new_link").html(result);

});
});
</script>

</body>

So the idea is the ajax link, when clicked, will send data to the server (data not shown here, I stripped all extraneous info I could), then the server will return one or more unique hyperlinks. That is all working. The problem is that the hyperlink that the ajax request creates, inside of the #new_link div, does not look like localhost:5000/next_page as I expect. Instead it looks like localhost:5000/{{ url_for('next_page') }} . It isn't being converted to the correct hyperlink, though I think I'm using the right format. I've looked for any possible errors I could be making by mistyping the url, but I can't find any. I suspect my error has something to do with sending the new urls in via ajax, but I'm kind of stuck in my troubleshooting. Can anyone help out?

Thanks.

/r/flask
https://redd.it/5xax19