TenebrisNocte
TenebrisNocte

Reputation: 179

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?

Upvotes: 4

Views: 2275

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26360

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()
    ......

Upvotes: 6

Related Questions