Code: Select all
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
Code: Select all
<?php
if ($_FILES['files']) {
$total = count($_FILES['files']['name']);
$data = array();
$errors = array();
for($i = 0; $i < $total; $i++) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if ($tmpFilePath != "") {
$newFilePath = "../uploads/" . $_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo json_encode(array('success' , 'Yup Done'));
} else {
$errors['files'] = 'You need to upload a file';
}
}
}
$data['success'] = 'Files have been uploaded successfully';
json_encode($data);
} else {
$errors['files'] = 'You need to upload a file';
$data['errors'] = $errors;
json_encode($data);
}
?>
Code: Select all
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
$.each(files, function(key, value){
data.append(key, value);
});
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
in my console , i get the following under response text in the ajax message:
Code: Select all
<br />↵<b>Notice</b>: Undefined index: files in <b>C:\xampp\htdocs\parselyJS\mail\filesend.php</b> on line <b>4</b><br />↵
Thank you.
Gautam.