Reputation: 11
I am going to be using AJAX via jQuery to generate some datafiles for a work project. I am planning on using Perl as the AJAX script. I wasn't sure how to send the data back to the calling program. So I decided to try a simple script just to get started. I found one on this site at How to send data to Perl script via ajax?
I copied the files as is to my working environment. I'll include them here: test.html:
<!DOCTYPE html>
<html>
<head>
<title>Testing ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").click(function(){
var ID = 100;
$.ajax({
type: 'POST',
url: '/cgi-bin/ajax/stackCGI/ajax.pl',
data: { 'data_id': ID },
success: function(res) {
alert("your ID is: " + res.result);
},
error: function() {alert("did not work");}
});
})
})
</script>
</head>
<body>
<button id="test" >Testing</button>
</body>
</html>
And here is ajax.pl:
#!/usr/bin/perl
use strict;
use warnings;
use JSON; #if not already installed, just run "cpan JSON"
use CGI;
my $cgi = CGI->new;
print $cgi->header('application/json;charset=UTF-8');
my $id = $cgi->param('data_id');
#convert data to JSON
my $op = JSON -> new -> utf8 -> pretty(1);
my $json = $op -> encode({
result => $id
});
print $json;
When I first ran it, I got the message error function denoting "did not work". Makes sense since the URL parameter was wrong. I changed the parameter to point to the proper path of the file and then made sure the Perl program had execute permission. That did lead me to running the success function, but I didn't get any data back from the Perl program.
I ran the ajax.pl from the command line, and it ran with no errors. I hard corded a return value, and still I got no data back. I put an intentional syntax error in the Perl code, and when I called it via the web page, I still got the success message. When I removed execute permissions from the file, I did get the message indicating an error "did not work".
I'm not sure if there needs to be a special server setting enabled for me to use ajax, or a special directory I need to put the Perl file in. I've done a good deal of searching on that issue, and I never found any restrictions, just warnings on making sure I'm specifying the location properly, which I am. I should note that the Perl script is in the same directory as the HTML file. It's not in a cgi-bin directory.
Upvotes: 1
Views: 644
Reputation: 63
your code is perfectly fine. I tested it works you need to make sure your perl script path is correct
"/cgi-bin/ajax/stackCGI/ajax.pl" means your script is at yourdomain.com/cgi-bin/ajax/stackCGI/ajax.pl
Linux is case sensitive so make sure your physical path is in same case.
You can try accessing that script directly in browser and it should return
{
"result" : null
}
Upvotes: 1