Use AJAX to upload a file, process, and return a result to Javascript using Flask

ajax, flask, javascript, jquery, python

Solution

You don't say what you want to achieve (hide some div, scroll window ...), and that's a main problem. To sum what should be done : Don't return

return render_template('index.html')

but fe. if you want to notify the user about the upload status, make status for this call like

return Response('OK')

or other status - NOTOK or something. Then in the js :

    success: function(data) {
        console.log('Success!');
    },

manipulate the response

if (data == 'OK') {
  alert ('YAY, FILE UPLOADED');
};

Problem

I've figured out how to upload a file using AJAX and Flask such that the page doesn't refresh and the file is uploaded to the server in some specified directory. In the Python method (upload()), I want to process the filename with some regex and return an array to the Javascript file. Do I still return render_template(index.html), even if I'm trying to request an array? HTML (index.html) ``` <form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data"> <div class="modal-body"> <label for="file"><b>Upload packet here</b></label> <input type="file" name="file"> <p class="help-block">Upload a .pdf or .docx file you want to read.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button id="upload-file-btn" type="button" class="btn btn-primary" data-dismiss="modal" value="Upload">Upload</button> </div> </form> ``` Javascript ``` $(function() { $('#upload-file-btn').click(function() { var form_data = new FormData($('#upload-file')[0]); $.ajax({ type: 'POST', url: '/uploadajax', data: form_data, contentType: false, cache: false, processData: false, async: false, success: function(data) { console.log('Success!'); }, }); }); }); ``` Python (Flask) ``` @app.route('/uploadajax', methods=['POST']) def upload(): file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return render_template('index.html') ``` I'm playing around with adding this AJAX call in the Javascript after the $.ajax{} part, but did I do it right? I'm not sure if I can call the same Python method twice in one Javascript function, or if there's an entirely better way to do this. ``` ajaxRequest = ajaxFunction() ajax.onreadystatechange = function() { if (ajaxRequest.readyState === 4) { if (ajaxRequest.status === 200) { alert(ajaxRequest.responseText) //I want the Python to put the array into this ajaxRequest.responseText variable, not sure how. } else alert('Error with the XML request.') } } ajaxRequest.open("GET", 'uploadajax', true); ajaxRequest.send(null); ``` Any help? Thanks.

Original source