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);

$.ajax({
url: "{{ url_for('encode') }}",
type: 'POST',
data: formData,
async: false,
success: function (data) {
$("#img-2").attr("src", "{{url_for('static', filename='encoded.png')}}");
$("#diff").show();
},
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']
img.save("./static/original.png")
secret = lsb.hide(img, a)
secret.save("./static/encoded.png")
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) {
    event.preventDefault()
    ......