I'm trying to call a JavaScript function on a button in html. Both the button and the JavaScript function are in the same file, however I am having an error saying that the function is not available.
function countFiles() {
$directory = "/uploadFiles";
$filecount = 0;
$files = glob($directory.
"*");
if ($files) {
$filecount = count($files);
}
if ($filecount > 0) {
echo '<script type="text/javascript">',
'window.location.href = "decrypt.php";',
'</script>';
} else {
echo "<script type='text/javascript'>alert('Precisa de inserir pelo menos 1 ficheiro');</script>";
}
}
<button onclick="countFiles()">Desencriptar</button>
From your comment,
I want call a function in html button. This function counts the number of files that a directory has. If number of files > 1 the page is redirect.
You can achieve this with an asynchronous call to PHP - through AJAX.
Method 1: Asynchronous call
<script>
function countFiles() {
$.ajax({
url: "getFileCount.php",
success: function(result) {
if (result.count > 0) {
window.location.href = "decrypt.php";
} else {
alert('Precisa de inserir pelo menos 1 ficheiro');
}
}}
);
</script>
Then, create a file called getFileCount.php
header('Content-Type: application/json');
$directory = "/uploadFiles";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
$filecount = count($files);
}
echo json_encode(['count' => $filecount]);
Method 2
However, if you don't expect the number of files to be changed between the page load and the click of the button, you don't need AJAX,
<?php
$directory = "/uploadFiles";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
$filecount = count($files);
}
?>
<script>
function countFiles() {
var fileCount = <?php echo $filecount; ?>;
if(filecount > 0){
window.location.href = "decrypt.php";
}else{
alert('Precisa de inserir pelo menos 1 ficheiro');
}
}
</script>