I am studying the php scandir method trying to return to javascript the result as an array. I read here many answers about Ajax fetch but because of my fault I didn't quite understand how to pass the headers between js and php. From php (I copied the scandir code from https://www.php.net/manual/en/function.scandir.php) 'echo json_encode ($ arrDir)' returns 'content-type = text / html' and instead of the array contents I receive the php file code as text. Can you please help me to understand what I did wrong and how can I get the array values? If possible in Vanilla JS. Thanks in advance
var arrDir = []; // array with directories to be returned
let url = "/testscan.php";
let response = fetch(url)
.then(response => {
const contentType = response.headers.get('Content-Type');
console.log("result: " + response.status + "\ntype: " + contentType);
// iterates all headers and show
for (let [key, value] of response.headers) {console.log(`${key} = ${value}`);}
if (!response.ok) { // error
if(response.status == 404){console.log("file does not exist")}
throw new Error(response.status);
}
if (/text\/html/i.test(contentType)) {
return response.text()
.then(function(text) {
console.log(text);
})
} else if (/application\/json/.test(contentType)) {
return response.json()
.then(function(json) {
console.log(json);
})
}
})
.catch(function (err) { // .catch(error => {
// do something when error happens
});
file testscan.php
$dir = "/PRODUCTS";
$arrDir = array();
Scan($dir, $arrDir);
echo json_encode($arrDir);
function Scan($dir, $arrDir){
// Create array of current directory
$files = scandir($dir);
if(is_array($files)){
foreach($files as $val){
// Skip home and previous listings
if($val == '.' || $val == '..')
continue;
if(is_dir($dir.'/'.$val)){
$arrDir[$dir][] = $val;
Scan($dir.'/'.$val, $arrDir);
}
else{
$arrDir[$dir][] = $val;
};
};
};
return $arrDir;
};