Stringering
Stringering

Reputation: 101

Upload file via ajax

I'm trying this for days now! Nothing that seemed to work for others, worked for me! And I really have to have it done now.

So this is very basic:

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="browseFile" id="photo" />
    <input type="submit" id="send" />
</form>

As you can see, there is a HTML form with a file input and a submit button. For what I'm trying to make, I need to send the file from the input field instantly after changing the value of it to the server.

Let's skip the part of the event listeners and validation.

This is the javascript, that should be able to get the value of the input field and send it to the server:

var inputFilePhoto = document.getElementById("photo");
var imageFile = inputFilePhoto.files[0];

var formData = new FormData();             
formData.append("file", imageFile);

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: formData,
    contentType: false,
    processData: false,

    success: function (output) {
        document.write(output);
        alert("OK");
    },
    error: function () {
        alert("Error");
    }
});

As you can see, I'm using the FormData object, which was new for me a couple days ago. It works fine with text fields etc., but not for file input fields. I also tried to apply the whole form on this object (new FormData($("form")[0])), but this - again - ignored the input fields of type "file" as if they did not exist.

To come back to the example above: ajax.php does nothing than debugging $_POST. So this is ajax.php:

<?php

echo '<pre>';

var_dump($_POST);
echo '</pre>';

The result of this is an empty array array(0) { }

Technical details: Tested on Chrome v48 on Mac OS X 10.11, using jQuery 2.2.0

I hope someone can finally help me with this, I accept solutions that use js plugins too.

Upvotes: 0

Views: 174

Answers (1)

Quentin
Quentin

Reputation: 943108

Data from file inputs appears in the $_FILES superglobal, not $_POST, when form data is parsed by PHP.

Upvotes: 2

Related Questions