What's new
HTML Forums | An HTML and CSS Coding Community

Welcome to HTMLForums; home of web development discussion! Please sign in or register your free account to get involved. Once registered you will be able to connect with other members, send and receive private messages, reply to topics and create your very own. Our registration process is hassle-free and takes no time at all!

AJAX and PHP - simple script only partly working

lianergoist

New member
Hello

I have made a simple PHP script that reads a directory and return the folder names. It also add on onClick event to the names, and that part is only partly working.

I load index.php and click the button. This start the function showDirs with current working directory as parameter. The function showDirs call list_dirs.php and the names of the directories are written to the screen ($dir) and also added an event trigger that will call call showDirs with the directory as parameter:

Code:
$path = "'" . $cwd . '/' . $dir . "'";
echo '<p class="dirs" onclick="showDirs(' . $path . ')">' . $dir . '</p>' . "\n";

So far everything works as expected. I can see the path is correct, and the directories are listed. And, when I click on the directory names, the onClick handler is working, and is sending the new path to showDirs. But the problem is; now is no (sub-)directories listed! The line
Code:
echo $q;
in list_dirs.php tell me the path is correct, but for some odd reason the directories are not listed.

What am I missing here?

See it in action: here Note: in the directory "files" is there a subdir names subdir.


index.php:

Code:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>test</title>
<script>
    function showDirs(str) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("dirs_div").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "list_dirs.php?q=" + str, true);
        xmlhttp.send();
    }
</script>
</head>
<body>
        <h1 id="header">test</h1>
        <button type="button" onclick="showDirs('<?php echo getcwd(); ?>')">test</button>

        <div id="dirs_div"></div>
</body>
</html>



list_dirs.php:

Code:
<?php

// get the q parameter from URL
$q = $_REQUEST["q"];

        $cwd = $q;
        $dirs = scandir($cwd);
        $i = 0;
        echo $q;
        foreach ($dirs as $dir)
        {
            if (is_dir($dir) && $dir != ".." && $dir != ".")
            {
                $path = "'" . $cwd . '/' . $dir . "'";
               
                echo '<p class="dirs" onclick="showDirs(' . $path . ')">' . $dir . '</p>' . "\n";

            }
        }
?>
 
Back
Top