LiggyRide
LiggyRide

Reputation: 71

Building FormData object from form

My FormData object will not get data from my pages form element. The appended data goes through and is displayed when I do a var_dump($_POST) in the PHP file, however the form data is not there. Without the append, it is just an empty array.

Javascript:

$(function() {
    $("form").on("submit", function() {
        var formData = new FormData($("#form")[0]);
        formData.append("Hello world", "This is a test");
        $.ajax({
            url: "sub/addCrane.php",
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
        })
        .done(function(data) {
            $("#form").append(data);
        });
    });
});

HTML form:

<form id="form" enctype="multipart/form-data" action="#">

    <p class="inline">Crane Model: </p><input type="text" id="model"><br />
    <p class="inline">Crane Brand: </p><input type="text" id="brand"><br />
    <p class="inline">Crane type (ie. Crawler, Tower, Mobile): </p><input type="text" id="type"><br />
    <p class="inline">Image of crane: </p><input type="file" id="image">
    <input type="submit" id="submit">

</form>

Upvotes: 3

Views: 3409

Answers (2)

Brotheryura
Brotheryura

Reputation: 1188

Try next:

$("#form").submit(function () {

var formData = new FormData();
jQuery.each($('#image')[0].files, function(i, file) {
    formData.append('file-'+i, file);
});

        $.ajax({
            type: "POST",
            url: 'sub/addCrane.php',
            data: formData,
            success: function (answer) {
                console.log(answer);
            }
        });
        return false;
    });

Upvotes: 0

Christopher Wirt
Christopher Wirt

Reputation: 1116

Your issue is that you're using id instead of name in your input tags, which doesn't let JQuery play nice with them, and so it ignores them. Also, it's not common practice, and PHP doesn't really like it either :)

Cheers!

Upvotes: 1

Related Questions