I have a script that detects if the file upload contains a file or not. So if a user press the upload button it will tell the user if the file upload contains a
file or not but the problem I can't figure out is, why am I getting an error when I try to upload with no file I assumed it would generate the if condition saying
No file detected in upload
but instead it gives me this error
Notice: Undefined index: image in etc../x.php on line 3
and for some reason it still executes the else condition combine with the above error
Detected
It does not makes sense to me. What am I doing wrong? How can I get it to produce the right condition without no errors?
Here is my code
index.php
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('upload').addEventListener("click",executeAjax);
function executeAjax(){
var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
document.getElementsByClassName('output-container')[0].innerHTML= xhr.responseText;
}
}
var data = new FormData();
//Var structure
var image= document.getElementById('image').files[0];
data.append('image',image);
xhr.open('POST','x');
xhr.send(data);
}
});
</script>
<input id='image' type='file'>
<button id='upload'>Upload</button>
<div class='output-container'><div>
x.php
<?php
if($_FILES['image']['error'] == 4)
{
echo 'No file detected in upload';
}
else{
echo 'Detected';
}
?>
Documentation for value 4 link