[FIXED] How do I get my ajax POST (preventDefault) to work?


I am trying to upload a csv file to a Flask server and I do not want the page to be reloaded, so I am trying to implement ajax. However, I cannot get it to work. Here is a minimal working example.


import os.path
from flask import Flask, render_template, request
app = Flask(__name__, static_url_path='', static_folder='static', template_folder='templates')
app.config['UPLOAD_FOLDER'] = './upload/'

@app.route("/", methods=["POST", "GET"])
def home():
    if request.method == "POST":
        f = request.files['todo']
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], 'upload.csv'))
        return 'this should not be printed'
    return render_template('index.html')

if __name__ == '__main__':


<!DOCTYPE html>
  <form method="post" id="todo-form" enctype="multipart/form-data">
    <input type="file" name="todo" id="todo">
    <button type="submit">submit</button>
  <script src="https://code.jquery.com/jquery-3.5.1.js"
  <script src="test.js"></script>


$(document).on('submit', '#todo-form', function(e) {
  const fd = new FormData(this);
    type: 'POST',
    url: '/',
    data: fd,
    contentType: false,
    processData: false,
    complete: function() { alert('saved');},

The reloading action is now prevented, and the alert is now shown, but the file is not uploaded. Can someone tell me what I did wrong? Thank you very much!


As pointed out by Phil, this is caused by the storage of browser cache. The code works as intended once the cache is cleared.

Answered By – cssstudent

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published