Fetch file php from js (vanilla) and return array (scandir or RecursiveIteratorIterator)

200 Views Asked by At

Fetch file php from js (vanilla) and return array (scandir or RecursiveIteratorIterator)

I try to fetch an external php file and return an array to javascript. It works well in local server but not in remote where the result is always:

Error SyntaxError: Unexpected token < in JSON at position 0

If you give me an example to pass data to php and return an array I would be happy with it. I attach files index.html and testscan.php which are not 'THE best' but simply 'MY best' (I appreciate any answers/solutions that can help me to understand and to go on studying JS. I apologize if there are other answers, I have read hundreds but I could not solve the problem. I ask to be patient, I am 75 y.o. and programming is only a hobby for me, when I was young computers didn't exist yet and now my mind is no longer very elastic)

<script>

var j, i;
var arrdir = [];                            // array with directories to be returned
let pth = "testscan.php";                   // file php that executes 'scandir'
let dir = "directory_name";                 // directory to be scanned

FetchDirectory(pth,dir)
.then((response) => {
    console.log("result: " + response.status + "\ntype: " + response.headers.get('Content-Type'));
    if (!response.ok) {
        if(response.status == 404){console.log("file does not exist")}
            throw new Error(response.status);
        }
    // return response.text();
    // return response.json();
    // console.log(response.text());
    return response;
})

.then(response => response.json())
.then(arrdir => { 
    // only to show results
    console.log("Total values: " + (arrdir.length) + "\n"); for(i = 0; i < arrdir.length; i++){console.log(i + " - " + arrdir[i] + "\n")};
})
.catch(function (err) {
    console.warn('Error ', err);
    // console.error(err);                  // this returns Syntax error in console
});

async function FetchDirectory(pth,dir) {      
    const response = await fetch(pth, {
        method: 'POST',
        // headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
        // headers: {"Content-Type": "application/json"},
        // headers: {"Content-Type": "application/text"},
        headers: {"Content-Type": "text/html"},
        body: `dir=${dir}`
    });
    return response.json();   // la stringa JSON restituita viene parsata e convertita in oggetti JavaScript
};

</script>
header('Content-type: text/html');
$dir = $_POST['dir'];
$arrdir = startScan($dir);
echo json_encode($arrdir);

function startScan($dir){       
    $j = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($j as $index => $value) {
        preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $value);
        
        if((!($value == '.') && !str_contains($value, '._') && !str_contains($value, '..') && !str_contains($value, '.DS_Store'))){ 
            $value = str_replace(DIRECTORY_SEPARATOR,"/",$value);                           
            if (is_dir($value)) {                   // it is a folder
                if(substr($value, -1) == '.'){$value = substr($value, 0, -1);};         // delete last dot from folders
                $value = substr($value, 0, -1);                                         // delete last '/' from folders
                if($index > 0){
                    $arrdir[] = $value;
                };
            }
            else{   // it is a file
                $arrdir[] = $value;
            };
        };
    };
    return $arrdir;
};
0

There are 0 best solutions below