Reputation: 1097
I am a complete newbie to Perl & Javascript/Jquery/Ajax. As an example, I'd like to send the string var exampleString
to test.pl, and the script will then write the string to file.
function sendToScript{
var exampleString = 'this is a string';
$.ajax({
url: './test.pl',
data: exampleString,
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
}
test.pl
#!/usr/bin/perl -w
use strict;
#How do I grab exampleString and set it to $string?
open (FILE, ">", "./text.txt") || die "Could not open: $!";
print FILE $string;
close FILE;
Any help would be much appreciated.
Upvotes: 1
Views: 1556
Reputation: 20280
Here is an example using the Mojolicious framework. It can be run under CGI, mod_perl, PSGI or its own built-in servers.
#!/usr/bin/env perl
use Mojolicious::Lite;
any '/' => 'index';
any '/save' => sub {
my $self = shift;
my $output = 'text.txt';
open my $fh, '>>', $output or die "Cannot open $output";
print $fh $self->req->body . "\n";
$self->render( text => 'Stored by Perl' );
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
%= t title => 'Sending to Perl'
</head>
<body>
<p>Sending</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
%= javascript begin
function sendToScript (string) {
$.post('/save', string, function (data) { alert(data) });
}
$(function(){sendToScript('this is a string')});
% end
</body>
</html>
save that to a file (say test.pl
) and the run ./test.pl daemon
which will start the internal server.
Basically it sets up two routes, the /
route is the user-facing page which runs the javascript request. The /save
route is the one that the javascript posts the data to. The controller callback appends the full post body to the file and then sends a confirmation message back which is then displayed by the success javascript handler.
Upvotes: 0
Reputation: 4445
You probably want something like
var exampleString = 'this is a string';
$.ajax({
url: './test.pl',
data: {
'myString' : exampleString
},
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
});
and test.pl
#!/usr/bin/perl -w
use strict;
use CGI ();
my $cgi = CGI->new;
print $cgi->header;
my $string = $cgi->param("myString");
open (FILE, ">", "./text.txt") || die "Could not open: $!";
print FILE $string;
close FILE;
Upvotes: 2