0

Using this piece of code I can list all the file URLs inside the Folder_A and Folder_B and Folder_C :

<?php
function getDirContents($directories, &$results = array()){

    $length = count($directories);
    for ($i = 0; $i < $length; $i++) {

    $files = array_diff(scandir($directories[$i]), array('..', '.'));;
    foreach($files as $key => $value){
        $path = $directories[$i].DIRECTORY_SEPARATOR.$value;
        if(is_dir($path)) {
          getDirContents($path, $results);
        } else {
          $directory_path = basename($_SERVER['REQUEST_URI']);
          $results[] =  'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
        }
    }

    }

    return $results;
}


$directories = array("Folder_A", "Folder_B","Folder_C");

echo json_encode(getDirContents($directories));

And using the JavaScript code below we can log them in the console (And have access to them via javascript):

$(document).ready( function() {
        $.ajax({
            type: 'POST',
            url: '../test.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
            console.log(result);
            },
        });
});

I just want one simple thing that I can't find a solution by myself:

How can I define the Folders inside javascript instead of having them in PHP?

I mean instead of having this inside PHP code:

$directories = array("Folder_A", "Folder_B","Folder_C");

I want to have this in Javascript:

let directories = [ "Folder_A", "Folder_B","Folder_C"];

And return the same functionality.

1 Answer 1

1

Pass the directories as part of the data: parameter.

$(document).ready( function() {
    let directories = [ "Folder_A", "Folder_B","Folder_C"];
    $.ajax({
        type: 'POST',
        url: '../test.php',
        data: {id: "testdata", directories: directories},
        dataType: 'json',
        success: function(result) {
            console.log(result);
        },
    });
});

Then in PHP you can use $_POST['directories'] to get the array:

echo json_encode(getDirContents($_POST['directories']));
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure why. Check the Network tab of the console to see what's being sent and received.
I think space causes the problem, If I have Folder A the code doesn't work...if I have Folder_A code works fine?!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.