Thursday, 14 September 2017

jQuery ajax single file upload

I know this question has been asked a lot, and I tried at least 10 different codes to run this without success.
I'm trying to upload a single file with jquery.ajax, but it doesn't work.
the code below always outputs : 'please choose a file' because the file's name is not set or something



html:











jquery:



$(function(){

$(document).ready(function(){
var files;

$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event){
files = event.target.files;
};
$(':button').click(function(){
var formData = new FormData();
$.each(files, function(key, value){

formData.append(key, value);
});
alert(formData);
$.ajax({
url: 'check.php',
type: 'GET',
data: formData,
success: function(data){ $('#result').html(data); },
cache: false,
contentType: false,

processData: false
});
});
});
});


php:



if(isset($_GET['file'])){

$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}



I don't know what the problem is, I know it's in the FormData object creation because the alert- good to go, doesn't work.



BTW it is really important for me that it would be written in jQuery.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...