BDeGiglio BDeGiglio - 5 months ago 26
jQuery Question

Using Ajax to upload file

I have tried several variations of this (based on articles and other SO forums) to get this to work and I have narrowed it down to the fact that the data is getting lost when I try to send the form data to my PHP script. When I echo $_FILES["file"]["name"] it is empty.

I have tested and my ajax and php scripts are connected as I can return some data, just not any form data. This is obviously resulting in the files not being uploaded.

My current code is in reference to this forum (lee8oi's answer):
jQuery Ajax File Upload
I started a new forum because this question was asked 6 years ago.

html:

<form id="signUpForm" name="signUpForm" action="../functions/newUser.php" method="post">
<input type="file" class="su_photo" name="file" id="user-photo">
<input type="submit" id="sign-up" type="button" class="btn btn-primary btn-sm pull-right" value="Get Started">
</form>


js:

$('#signUpForm').on('submit',function(){
var fd = new FormData( $('#signUpForm') );
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "../../functions/newUser.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
});


php:

if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo $_FILES["file"]["name"];
}

Answer

I think you just need to change the following line

var fd = new FormData( $('#signUpForm') );

to

var fd = new FormData( $('#signUpForm')[0] );

or

var fd = new FormData(this);

The constructor of FormData expects a native form element, not a jQuery object. So document.getElementById('signUpForm'), $('#signUpForm')[0], and this would all work.

This answer provides further explanation.

Comments