Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
Ajax fetch external file php and return array to javascript

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;
};
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda