0

i want to fetch all the names of files from a folder/directory, create a json in php and call it in javascript. the final resulsts in javascript should be an array like this const alllabels = ['img/filename','img/filename','img/filename','img/filename']. so far I get the file names and I can create a JSON in PHP. but am having trouble manipulating the JSON in the javascript file. below is my code.

$data = array();
foreach(glob('img/*.*') as $filename){
    $name = $filename;
    $data[] = array($name);

}
echo json_encode($data);

my javascript function is as below

const labels = [];
function getlabels() {
    $.ajax({
        type: "POST",
        url: "get_labos.php",
        data: "",
        success: function (html) {
            var results = Json.parse(html);
            labels = results;
            return labels;

        }

    })

}

const alllabels = [getlabels()];

i need alllabels to be an array like this. ['img/filename','img/filename','img/filename','img/filename'].

Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
Wateya
  • 39
  • 3
  • `echo json_encode(glob(…));` would have gotten you the result you need here. But instead of simply encoding the array of file names you already got from `glob`, you are looping over it, and deliberately create an _array of arrays_. – CBroe Jul 22 '20 at 08:41
  • What _won’t_ work this way though, is your JS part, you can not return a value from an async call like this. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – CBroe Jul 22 '20 at 08:43
  • could you please help me with a demo code both php code and javascript. – Wateya Jul 22 '20 at 08:52

0 Answers0