Reputation: 31
I want to call a Perl script from JavaScript. The Perl script moves/copies a file from one folder to another. But when I try to call it it's not running.
I am new in this field so a little help will do a lot to me.
copy_file.pl
#!/usr/bin/env perl
use strict;
use warnings;
use File::Copy;
my $source_dir = "/home/Desktop/file";
my $target_dir = "/home/Desktop/Perl_script";
opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";
my @files = readdir($DIR);
foreach my $t (@files) {
if (-f "$source_dir/$t" ) {
# Check with -f only for files (no directories)
copy "$source_dir/$t", "$target_dir/$t";
}
}
closedir($DIR);
home.html
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>Click Date to display current day, date, and time.</p>
<button type="button" onclick="myFunction()">Date</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
$.get("copy_file.pl");
}
</script>
</body>
</html>
Upvotes: 0
Views: 3732
Reputation: 769
This looks like CGI/Apache issue. For the Perl code to run correctly in an Apache environment you need to return a Content Type header as one of the first things that your code outputs. Try using code that looks more like this...
#!/usr/bin/env perl
use strict;
use warnings;
print "Content-Type: text/html\n\n";
use File::Copy;
use CGI::Carp qw(fatalsToBrowser); #nice error handling, assuming there's no major syntax issues that prevent the script from running
my $source_dir = "/home/Desktop/file";
my $target_dir = "/home/Desktop/Perl_script";
opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";
my @files = readdir($DIR);
foreach my $t (@files) {
if (-f "$source_dir/$t" ) {
# Check with -f only for files (no directories)
copy "$source_dir/$t", "$target_dir/$t";
}
}
closedir($DIR);
print "<h1>OK</h1>\n";
print "<p>Print</p>\n";
__END__
Also, it goes without saying that you need to make sure that the script need to also be marked as executable on the file system and Apache needs to have the privs to run it. Once you have checked all of this run the script from the URL line to make sure you are getting some sort of output before trying to call the script from JavaScript.
From the JavaScript perspective, you need to also include a link to jQuery if you want the JavaScript code to work correctly, as Quentin correctly points out. Try adding the following header section (and include) above your Body section...
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
Upvotes: 2
Reputation: 944434
If you look at your JavaScript error console you will see that it is complaining that $
is not defined.
You appear to be trying to use jQuery, you need to include the library for it in your page before you can use the functions it provides.
<script src="path/to/where/you/put/jquery.js"></script>
Upvotes: 1