I send files via fetch and uploading them in PHP with move_uploaded_file() method.The problem is when i use move_uploaded_file() method page automatically refresh and even when i upload multiple files just first one uploading and refresh page again.
PHP Codes
if($img['error'] == 0 && $img['size'] > 0){
if (!is_dir('naber')) {
mkdir('naber', 0777, true);
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
// $extension = explode(".", $_FILES["image"]["name"]);
// $extension = end($extension);
$extension = pathinfo($img['name'])['extension'];
if(!(in_array($extension, $allowedExts))){
$result['status'] = false;
$result['errmessage'] = 'Image type is invalid';
exit(json_encode($result));
}
$target_path = 'naber/';
$filename = time().'.'. strtolower($extension);
$full_path = $target_path."".$filename;
if(move_uploaded_file($img['tmp_name'], $full_path)){
$result['status'] = true;
$result['message'] = 'Image added successfully!';
}else{
$result['status'] = false;
$result['errmessage'] = 'Image type is invalid';
exit(json_encode($result));
}
}
exit(json_encode($result));
Javascript codes :
if(document.querySelector('#submit')) document.querySelector('#submit').addEventListener('click', (e) =>{
e.preventDefault();
...
fd = new FormData();
Array.from(document.querySelectorAll('.test')).some((t) => {
.......
tests['test'+i]['img'] = t.querySelector('.input-ifile').files[0];
fd.append('test'+i+'-img',tests['test'+i]['img']);
.......
fetch('handlers/handler.php', { method: 'POST' , body: fd})
.then(function (response) {
return response.text();
})
.then(function (body) {
console.log(body)
return false;
});
})
Desired outcome is for the file to be uploaded to the server, and index.php not be refreshed.
Solution : After spending hours to find problem so figured out that problem is not in the codes. It was happening because of Visual Studio Live Server extension. For prevent auto reloading just closeing live server is enough.