I try to submit form with file with jQuery.ajax
. Google says I should use FormData
which will automagically encode the file and all inputs into the one object which I can send via XHR.
Well, the FormData
object is empty. It’s empty in the debugger and on the server side. I can’t find the error. Here is the code. The browser is Firefox 27.
JavaScript
x
37
37
1
<form method="post" action="" enctype="multipart/form-data" id="generate_params">
2
<input type="hidden" name="id" value="1">
3
<input type="hidden" name="action" value="AJAX_BANNERS_GENERATE">
4
</form>
5
6
<div>
7
<p>
8
<label>
9
Image: <input type="file" name="bg_image[]" form="generate_params" required>
10
</label>
11
</p>
12
</div>
13
14
<input type="submit" form="generate_params">
15
16
<script>
17
$(document).ready(function () {
18
$("#generate_params").submit(function (e) {
19
var data = new FormData(this);
20
21
$.ajax({
22
data: data,
23
method: "POST",
24
success: function (url) {
25
alert("ok");
26
},
27
cache: false,
28
contentType: false,
29
processData: false
30
});
31
32
e.preventDefault();
33
return false;
34
});
35
});
36
</script>
37
In Firebug on the Network
tab in the Params
section I see the line:
[object FormData]: "undefined"
? Seriously?
The silly thing that I can’t even send FormData
object created from scratch. Like this
JavaScript
1
3
1
var data = new FormData();
2
data.append("test", {value: 0}); // still empty
3
Advertisement
Answer
Turned out, I’m using jQuery 1.8.1 which doesn’t support FormData
. Library update solved the problem.