/    Sign up×
Community /Pin to ProfileBookmark

Finding the files in a subdirectory using javascript and php

I have modified an existing piece of javascript code with an XMLHttpRequest, to fill an array with the names of the subdirectories in a folder “Year”. (full html/script code below). The first time I press the button, it does not find any. But pressing the button a second time, it finds all the sub-directories in the folder. I have no idea why it does not find the subdirectories the first time.

In an earlier question of mine involving an XMLHttpRequest (link below) Sempervivum very kindly showed me how to replace the XMLHttpRequest code using a “Fetch” command
https://www.webdeveloper.com/d/392350-how-to-encode-text-to-stop-php-fputcsv-changing-plus-signs

So, is it possible to replace the code below with the fetch command? If not, can you see why it does not return the answer the first time? Thanks (apologies – I have tried several times to get the code below to show as code – but have failed miserably!)

[code]
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button </p>
<br>
<button type=”button” onclick=”myFunction()”>Find number files in Year</button>
<script>
var fileList=[];
function myFunction(){
//looks at all the subdirectories in the folder “Year”
getData(“Year”);
var temp =fileList.length;
var temp =String(temp);
alert(temp);
}
function getData(dsub){
var hr = new XMLHttpRequest();
var params = “Dname=”+dsub;
hr.open(‘POST’,’readdirs.php’,true);
hr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var rObj = JSON.parse(hr.responseText);
for(var i=0;i<rObj.length;i++){
fileList[i]= String(rObj[i]);
}
}
};
hr.send(params);
}
[/code]

This is the php file on the server – readdirs.php

[code]
<?php
$dir = “Subjects/”;
$dirList = array();
// Open a directory, and read its contents
if(isset($_POST[“Dname”])){
$dir = ($_POST[“Dname”]);
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file == “.” || $file == “..”){
continue;
}
array_push($dirList,$file);
}
closedir($dh);
}
echo json_encode($dirList);
}
}
?>
*/
</script>
</body>
</html>
[/code]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJan 17.2021 — Code tags: `your code here` will work reliably. I edited your posting accordingly.

This is an issue that occurs frequently: Ajax requests are working asynchronously, i. e. the request is sent to the server and then it takes a short time until the response is received. If you use the response right after the call it has not yet been received. When you perform the request a second time the response from the first one is there and the data is available.

In order to fix this, you have to perform all actions that are using the data from the response, in the callback:
function getData(dsub) {
var hr = new XMLHttpRequest();
var params = "Dname=" + dsub;
hr.open('POST', 'readdirs.php', true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 &amp;&amp; hr.status == 200) {
var rObj = JSON.parse(hr.responseText);
for (var i = 0; i &lt; rObj.length; i++) {
fileList[i] = String(rObj[i]);
// You have to perform all actions that use the
// response here:
var temp = fileList.length;
var temp = String(temp);
alert(temp);
}
}
};
hr.send(params);
}
getData(dsub);
// when using the data delivered by the response here it will not have been received yet.
Copy linkTweet thisAlerts:
@DeanleeJan 17.2021 — I want to be able to list all the directories, subdirectories and files in the "./" folder ie the project folder called fileSystem which contains this php file scanDir.php.

At the minute it will only return the subdirectory folders/files in the root of the mkdir directory but not any folders inside that subdirectory.

**Links removed by Site Staff so it doesn't look like you're spamming us. Please don't post them again.**
Copy linkTweet thisAlerts:
@IanRauthorJan 17.2021 — @Sempervivum#1626873

Thanks again Sempervivum - I should have remebered that!
×

Success!

Help @IanR spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...