Click here to Skip to main content
14,980,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Desired outcome is the file to be uploaded to the folder and current page not be refreshed. By the way i working on localhost.

What I have tried:

PHP Codes

if($img['error'] == 0 && $img['size'] > 0){
        if (!is_dir('naber')) {
            mkdir('naber', 0777, true);
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $extension = pathinfo($img['name'])['extension'];
        if(!(in_array($extension, $allowedExts))){
            $result['status'] = false;
            $result['errmessage'] = 'Image type is invalid';
        $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!';
            $result['status'] = false;
            $result['errmessage'] = 'Image type is invalid';

Javascript codes :

if(document.querySelector('#submit')) document.querySelector('#submit').addEventListener('click', (e) =>{
    fd = new FormData();
    Array.from(document.querySelectorAll('.test')).some((t) => {
                tests['test'+i]['img'] = t.querySelector('.input-ifile').files[0];
    fetch('handlers/handler.php', { method: 'POST' , body: fd})
    .then(function (response) {
        return response.text();
    .then(function (body) {
        return false;
Updated 18-Mar-21 4:27am

1 solution

I do not think it is your code that refresh page but your server that "listens" to file changes, if a folder has changed it will refresh your pages.

See more on subject HERE.

You probably have server on watch mode. so when you upload a file, the watcher detects something change on disk and reload.

find that option and turn it off.

alternatively, some watchers have option to ignore certain folder. you can add that images folder to ignore list.

to disable watch mode for certain files/folders, do like this

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900