I'm trying to do this scenario . If folder is empty then return false else return true . To do that i tried this
function downloadExcel() {
// Mu folder path
var folder="D:/output";
if (result.isConfirmed) {
$.ajax({
type: 'POST',
url: 'check_file.php',
data: {
folder: folder
},
cache: false,
success: function(result){
if(result==false)
{
Swal.fire(
'execution success '
);
}
else
{
Swal.fire(
'extraction failed '
);
}
},
error: function(result){
console.log("Error request Ajax");
}
});
refresh();
} else if (
result.dismiss === Swal.DismissReason.cancel
my php file to render the data :: check_file.php
<?php
if (!empty($_POST["folder"])) {
$dir = $_POST['folder'];
}
if (is_dir_empty($dir)) {
echo "the folder is empty";
$result=false;
}else{
echo "the folder is NOT empty";
$result=true;
}
return $result;
function is_dir_empty($dir) {
if (!is_readable($dir)) return null;
return (count(scandir($dir)) == 2);
}
?>
When i run my check_file.php the check if directory is empty or not works fine .
But when i try the the $result variable there something gone wrong about my code
The $result variable is always empty
CodePudding user response:
You're never echoing
$result
- and even if you did, echoing a booleanfalse
doesn't actually produce any visible output. Usingreturn
to end the main part of a script isn't necessary, doesn't really make much sense and certainly doesn't produce any output.The things you are echoing consist of neither
true
norfalse
, so obviously the JS code won't match those either.To allow the JS to detect a truth-y or false-y value accurately, it's better to output numeric
0
or1
than strings.As an additional point, it would make sense not to try and use
$dir
unless it's been populated.
This version should help you (note that if there's no value in $_POST["folder"]
it won't output anything - you might want to add something extra to deal with that, but I'll leave it up to you):
<?php
if (!empty($_POST["folder"]))
{
$dir = $_POST['folder'];
$result;
if (is_dir_empty($dir)) $result = 0;
else $result = 1;
echo $result;
}
function is_dir_empty($dir) {
if (!is_readable($dir)) return null;
return (count(scandir($dir)) == 2);
}
?>