I'm trying to create a file uploader inside a Sweet Alert 2 modal with jQuery and php. Here's my code, but it isn't working: how can I get this working?
Thank you
HTML (the button to open the modal with Sweet Alert 2):
<button class="bx--btn bx--btn--primary" type="button" id="swal_upload">Apri</button>
JavaScript:
$('#swal_upload').click(function(){
var api = 'api/UploadFile.php';
swal({
title: "Carica immagine",
html: '<input id="fileupload" type="file" name="userfile">'
}).then(function() {
var formData = new FormData();
formData.append('userfile', $('#fileupload').val().replace(/.*(\/|\\)/, ''));
console.log(formData);
$.ajax({
type: 'POST',
url: api,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
headers: {"Content-Type":"form-data"},
async: true,
success: function(result){
console.log("OK client side");
console.log(result.Response);
}
});
})
});
php (api/UploadFile.php):
$entered = "PHP started";
$tmpFilePath = $_FILES['userfile']['tmp_name'];
$uploaddir = 'public/';
if ($tmpFilePath != ""){
$newFilePath = $uploaddir . basename($_FILES['userfile']['name']);
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$uploaded = "Upload OK server side";
} else {
$uploaded = "Upload failed server side";
}
}
// Prepare response, close connection and send response to front-end
$array['Response'] = array(
'entered' => $entered,
'tmp_path' => $tmpFilePath,
'new_path' => $newFilePath,
'file_name' => $_FILES['file']['name'],
'uploaded' => $uploaded
);
echo json_encode($array);
The output I have in the console is:
FormData {}proto: FormData OK client side {entered: "PHP started", tmp_path: null, new_path: null, file_name: null, uploaded: null} entered:"PHP started" file_name:null new_path:null tmp_path:null uploaded:null proto:Object
As you can see the php starts, but no file is passed to the server.