TenebrisNocte TenebrisNocte - 1 month ago 9
Ajax Question

Don't reload webpage after flask ajax request

I have this ajax request

$(function() {
$('#left').bind('click', function() {
var form = $('form#data')[0]; //
var formData = new FormData(form);

url: "{{ url_for('encode') }}",
type: 'POST',
data: formData,
async: false,
success: function (data) {
$("#img-2").attr("src", "{{url_for('static', filename='encoded.png')}}");
cache: false,
contentType: false,
processData: false


And this flask function runs when the button is clicked.

@app.route('/encode', methods=['GET', 'POST'])
def encode():
a = request.form['text']
img = request.files['files']
secret = lsb.hide(img, a)
return "ok"

The problem I am having is that the webpage becomes for a split second as it should be the image is set and the button diff is shown. But after that the webpage reloads and resets to the index page. And I do not really know how to prevent that from happening. What am I doing wrong?

Answer Source

Blind guess : your button may be part of a form, so its default behaviour when clicked is to submit the form and reload the page. You can prevent that by using event.preventDefault() :

$('#left').bind('click', function(event) {