I am sending multiple form data as an formdata object using ajax to python flask. Just like the example here.
In the below code, I am sending data of two forms using ajax to flask. I can’t retrieve it on server side, However I managed to get files using request.files on python.
But I can’t retrieve or see the form data object which is appended to ajax request having id “form-2”.
How can I see the input values filled on second form in the back end.
<html> <body> <form id="form1"> <input type="file" name="file[]" multiple id="file-input" /> <form> <form id="form2"> <div class="preference"> <label for="cheese">Do you like cheese?</label> <input type="checkbox" name="cheese" id="cheese"> </div> <select name="course"> <option value="1">HTML</option> <option value="2">CSS</option> <option value="3">JAVA SCRIPT</option> </select> <form> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $("input[type='file']").on("change", function(ev) { ev.preventDefault(); // Prevent browser default submit. var form_data = new FormData() var all_files = document.querySelector('input[type=file]').files var totalfiles = all_files.length; for (var i = 0; i < totalfiles; i++) { console.log(all_files[i]); form_data.append("files[]", all_files[i]); console.log("Added " + (1 + i)+ " files in formdata"); } console.log("added all files completely! ...appending advance options"); var formdata2 = new FormData(document.getElementById('form-2')); form_data.append("advance_options", formdata2) console.log("successfully appended..calling ajax func"); send_request_to_flask(form_data); }); </script> <script> function send_request_to_flask(form_data_parameter){ $.ajax({ url: "http://127.0.0.1:5000", type: "POST", data: form_data, contentType: false, cache: false, dataType: 'json', processData:false, withCredentials:true, beforeSend: function(xhr) { }, xhr: function() { var xhr = $.ajaxSettings.xhr(); if(xhr.upload){ xhr.upload.addEventListener('progress', function(event){ var percent = 0; if (event.lengthComputable) { percent = Math.ceil(event.loaded / event.total * 100); } console.log(percent) }, false); } return xhr; }, success: function (msg) { console.log(msg) }, error: function(data){ console.log(data); } }); } </script> </body> </html>
Advertisement
Answer
You cannot append a form data object into another form data object, you have to append the fields from the second form into the first form data object.