Reputation: 87
I have a form which lets the user enter some text and when the user submit the form. that text gets returned and a image is generated by using PIL module of that text.
@app.route('/enter')
def index():
img = Image.new('RGB',(1000,1000))
txt=request.form['text']
font=ImageFont.truetype("ariel.ttf",30)
draw = ImageDraw.Draw ( img )
draw.text ( ( 0 , 0), txt, font=font, fill="#000000" )
io = StringIO()
img.save(io, format='png')
data = io.getvalue().encode('base64')
return render_template('index.html',data=data)
this dynamic image is then forwarded to the webpage where it is shown
<img src="data:image/png;base64,{{data}}" > // html shows the image
but this requires a reload or refresh of the page. Is it possible to use javascript or json to get the form data and render the image without refreshing the page. Also i am using tabs to display the content of the page and this img which get dynamically updated as per the user response is contained in #tab4 How do i set the url in flask:
@app.route('/enter#tab4', methods=[ 'POST'])
or simply
@app.route('/enter', methods=[ 'POST'])
Upvotes: 3
Views: 3640
Reputation: 564
Do something like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#cal').bind('click', function() {
$.getJSON('/t', {
aa: $('input[name="text"]').val(),
}, function(data) {
$('#result').html('<img src="data:image/png;base64,' + data.result + '" />');
});
return false;
});
});
</script>
and in the html:
<form>
<input type="text" size="5" name="text">
<span id="result">
</span>
<a href="javascript:void();" id="cal">calculate server side</a>
</form>
just make a function in your python code
@app.route('/t')
def pre():
tx = request.args.get('aa', 0, type=str)
//call function to perform some function on tx and then convert it to base64
return jsonify(result=data)
This should serve your purpose. There will be no reloading or refresh required.
Upvotes: 5