Home > other >  How to launch ajax function based on a condition in a javascript function
How to launch ajax function based on a condition in a javascript function

Time:02-10

I'm trying to launch an ajax call based on a condition (folder not empty) .

The result of my condition is working fine in php file check_file.php

Here is my check_file.php how it looks like

<?php

if (!empty($_POST["folder"])) 
{
$dir = $_POST['folder'];
$files = array_diff(scandir($dir), array('.', '..'));
$result;

if (!is_dir_empty($dir) && trim(substr( json_encode($files), 6, 2 )) == 'ok'  )  
{ 
$result = 0;  
}
else  {$result = 1;}

echo $result;
unlink($dir.'/'.trim($files[2])  )  ; 
}

function is_dir_empty($dir) {
if (!is_readable($dir)) return null; 
return (count(scandir($dir)) == 2);
}
?> 

In my JavaScript script this is how it looks like

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==0)
                        {
                            Swal.fire(
                                    'Execution  success , please check your email '
                            );
                        }
                        else
                        {
                            Swal.fire(
                                'Execution  en cours   '
                            );  
                        }
                        
                },
            error: function(result){

               console.log("Error request Ajax");
            } 
            });
            
            refresh();

        } else 
            result.dismiss === Swal.DismissReason.cancel
        }

I'm new to javascript , how could i test if folder is not empty launch the $.Ajax call

CodePudding user response:

  •  Tags:  
  • Related