user5600884 user5600884 - 1 month ago 8
jQuery Question

When uploading file via ajax, it always returns [ as file info

I have looked through many different questions and I still haven't been able to locate the flaw in my code. I basically am attempting to upload a file to the server using html/ajax and php for the server side. Below is my code:

//HTML
<div class="col-sm-6">
<div class="">
<input name="bugType" type="text" class="bugType">
</div>
</div>
<div class="col-sm-6">
<div class="upload">
<input name="bugImage" type="file" class="bugImage">
</div>
</div>

//JS
$("#addBug").on('click', function (event) {
event.preventDefault();
var bugType = $('input[name="bugType"]').val();
var imageName = $('input[name="bugImage"]');
fd = new FormData();
fd.append("type", "add");
fd.append("imageName", imageName);
fd.append("bugType", bugType);
$.ajax({
url: 'classes/bug-class.php',
type: "POST",
dataType: "json",
data: fd ,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (data) {
alert("SUCCESS");
alert(data);
},
error: function (data) {
alert("FAILURE");
console.log(data);
}
});
});



//PHP
$type = $_POST['bugType'];
$image = $_POST['imageName'][0];
echo $image; //PRINTS OUT [


If I change:

$image = $_FILES['imageName']
echo $image // PRINTS OUT ""


Thanks for the help!

//EDIT

FileList {0: File, length: 1}
0
:
File
lastModified
:
1475177716000
lastModifiedDate
:
Thu Sep 29 2016 14:35:16 GMT-0500 (CDT)
name
:
"17-3.png"
size
:
187682
type
:
"image/png"
webkitRelativePath
:


""
proto
:
File
length
:
1
proto
:
FileList

var_dump($_FILES) // output -> array(0)


//WORKING

had to change to this:

fd.append("imageName", imageName[0])


and then it worked!

Answer

You directly send the element to your SERVER.

var imageName = $('input[name="bugImage"]');


var imageName = $('input[name="bugImage"]')[0].files;