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
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);
}
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>