Skip to content

FormData is empty when using jQuery ajax()

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.

<form method="post" action="" enctype="multipart/form-data" id="generate_params">
    <input type="hidden" name="id" value="1">
    <input type="hidden" name="action" value="AJAX_BANNERS_GENERATE">
</form>

<div>
    <p>
        <label>
            Image: <input type="file" name="bg_image[]" form="generate_params" required>
        </label>
    </p>
</div>

<input type="submit" form="generate_params">

<script>
    $(document).ready(function () {
        $("#generate_params").submit(function (e) {
            var data = new FormData(this);

            $.ajax({
                data: data,
                method: "POST",
                success: function (url) {
                    alert("ok");
                },
                cache: false,
                contentType: false,
                processData: false
            });

            e.preventDefault();
            return false;
        });
    });
</script>

In Firebug on the Network tab in the Params section I see the line:

enter image description here

[object FormData]: "undefined"? Seriously?

The silly thing that I can’t even send FormData object created from scratch. Like this

var data = new FormData();
data.append("test", {value: 0}); // still empty

Answer

Turned out, I’m using jQuery 1.8.1 which doesn’t support FormData. Library update solved the problem.