I'm making a very simple file upload web application, i tested it with a simple POST request directly to the PHP page and it works fine but not with Ajax. I'm thinking it's related to the way i'm using FormData() but i did google and experiment with other solutions using the FormData but none of them worked so i'm not entirely sure where the problem lies. I just get this type of error in the console :
Object { readyState: 0, getResponseHeader: getResponseHeader(key), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(name, value), overrideMimeType: overrideMimeType(type), statusCode: statusCode(map), abort: abort(statusText), state: state(), always: always(), catch: catch(fn), … }
HTML :
<form id="upForm" enctype="multipart/form-data">
<input hidden name="MAX_FILE_SIZE" value="3000000">
<input id = "file" type="file" name="file"> <br>
<input type="submit" value="upload">
</form>
JS script :
$(document).ready(function (e) {
$("#upForm").on('submit', function (e) {
$.ajax(
{
type: 'POST',
dataType: 'JSON',
url: '/data/controls.php',
processData: false,
contentType: false,
cache: false,
data: new FormData(this),
// beforeSend: // TO-DO
success: function (response) {
// file uploaded
console.log(response);
},
error: function (response) {
console.log(response)
}
}
)
}
)
}
)
controls.php :
$uploadDir = "../upload/";
$response = array(
'status' => 0,
'message' => 'Oops!'
);
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//test file extension
//test file size
if ($_FILES['file']['size'] > 3000000){
$response['status'] = 0;
$response['message'] = 'File size too big!';
} else {
$allowedTypes = array('jpg', 'png', 'jpeg', 'gif');
$fileName = basename($_FILES['file']['name']);
$filePath = $uploadDir . $fileName;
$fileType = pathinfo($filePath, PATHINFO_EXTENSION);
if (in_array($fileType, $allowedTypes)){
if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath)){
$response['status'] = 1;
$response['message'] = 'Something went wrong :(';
}
} else {
$response['status'] = 2;
$response['message'] = 'File format not allowed!';
}
}
if ($response['status'] = 1){
$PDOinst= DBconnect::getInstance();
$PDO = $PDOinst->getConnection();
$sqlString = "INSERT INTO fileUpload values (NULL, :fname, :size, :upDate)";
$query = $PDO->prepare($sqlString);
$paramArray = array(
'fname' => $_FILES['file']['name'],
'size' => $_FILES['file']['size'],
'upDate' => date("d-m-Y (G:i)")
);
$query->execute($paramArray);
$response['status'] = 3;
$response['message'] = 'File uploaded successfully!';
}
echo json_encode($response);
}
echo json_encode($response);