I want to send data to Perl script via ajax, and to receive a json format back from it. But it doesn't work. I know something is wrong in the following scripts. Does anyone know how to fix it?
jQuery code:
$("#test").click(function(){
var ID = 100;
var data = {
data_id : ID
};
$.ajax({
type: "POST",
url: "ajax.cgi",
data: data,
success: function(msg){
window.alert(msg);
}
});
});
ajax.cgi (perl script):
#!/usr/bin/perl
use CGI;
use DBI;
$cgi = CGI->new;
# Here I'd like to receive data from jQuery via ajax.
$id = $cgi->param('data_id');
$json = qq{{"ID" : "$id"}};
$cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
exit;
Not sure whether you solved it by now but maybe someone else stumbles over this question and wonders how it works.
Please find the code below. If you want to run this code, just copy the index.html file to your html directory (e.g. /var/www/html) and the perl script to your cgi-bin directory (e.g. /var/www/cgi-bin). Make sure to make the perl script executable! In my code below, the cgi directory is in /cgi-bin/ajax/stackCGI - please change that accordingly.
I also added a slightly more advanced example on how to use Perl cgi, AJAX and JSON: click and also one more example on how to pass an array from Javascript to Perl via AJAX using JSON: click.
index.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>
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;
I think, you forgot to print header:
$cgi->header(-type => "application/json", -charset => "utf-8");
should be
print $cgi->header(-type => "application/json", -charset => "utf-8");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With