Home > Software engineering >  How do I get my ajax POST (preventDefault) to work?
How do I get my ajax POST (preventDefault) to work?

Time:09-14

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.

app.py

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__':
    app.run(debug=True)

templates/index.html

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

static/ajax.js

$(document).on('submit', '#todo-form', function(e) {
  const fd = new FormData(this);
  e.preventDefault();
  $.ajax({
    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!

CodePudding user response:

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

  • Related