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.
JavaScript
x
127
127
1
<html>
2
3
4
<body>
5
6
<form id="form1">
7
8
<input type="file" name="file[]" multiple id="file-input" />
9
10
<form>
11
12
13
<form id="form2">
14
15
<div class="preference">
16
<label for="cheese">Do you like cheese?</label>
17
<input type="checkbox" name="cheese" id="cheese">
18
</div>
19
20
<select name="course">
21
<option value="1">HTML</option>
22
<option value="2">CSS</option>
23
<option value="3">JAVA SCRIPT</option>
24
</select>
25
26
27
28
<form>
29
30
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
31
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
32
33
<script>
34
35
$("input[type='file']").on("change", function(ev) {
36
ev.preventDefault(); // Prevent browser default submit.
37
var form_data = new FormData()
38
var all_files = document.querySelector('input[type=file]').files
39
var totalfiles = all_files.length;
40
41
42
for (var i = 0; i < totalfiles; i++) {
43
44
45
console.log(all_files[i]);
46
form_data.append("files[]", all_files[i]);
47
48
console.log("Added " + (1 + i)+ " files in formdata");
49
50
51
52
53
54
}
55
56
console.log("added all files completely! ...appending advance options");
57
58
var formdata2 = new FormData(document.getElementById('form-2'));
59
60
61
form_data.append("advance_options", formdata2)
62
63
64
console.log("successfully appended..calling ajax func");
65
66
send_request_to_flask(form_data);
67
68
69
});
70
71
</script>
72
73
74
<script>
75
76
function send_request_to_flask(form_data_parameter){
77
78
79
80
$.ajax({
81
url: "http://127.0.0.1:5000",
82
type: "POST",
83
data: form_data,
84
contentType: false,
85
cache: false,
86
dataType: 'json',
87
processData:false,
88
withCredentials:true,
89
beforeSend: function(xhr) {
90
91
},
92
xhr: function() {
93
var xhr = $.ajaxSettings.xhr();
94
if(xhr.upload){
95
xhr.upload.addEventListener('progress', function(event){
96
var percent = 0;
97
if (event.lengthComputable) {
98
percent = Math.ceil(event.loaded / event.total * 100);
99
}
100
console.log(percent)
101
}, false);
102
}
103
return xhr;
104
},
105
success: function (msg) {
106
console.log(msg)
107
108
109
},
110
error: function(data){
111
112
113
console.log(data);
114
}
115
});
116
117
}
118
119
120
121
122
123
</script>
124
125
</body>
126
</html>
127
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.