3

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>
1
  • Check your response console.log(data)' in done()`? Commented May 9, 2014 at 0:02

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

5 Comments

Will this send the file also?
And sorry for the silly question, self teaching JQuery meant I missed a lot, but if my form is now <form name='myForm'> do I just call it in JQuery with $('myForm')?
Ah, sorry, let me clarify. You need to use 'name' in the input tags, though using a name for the form is also beneficial. To answer that question, though, yes, that's the selector you'd use
Thank you so much! First question on stackoverflow and it went so well!
Come back more often, we're mostly really nice :D
0

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;
    });

1 Comment

formData is not defined in the example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.