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;
use strict; use warnings→ declare your variables. (2) You don't actuallyprintthe$cgi->header(...), as far as I can see. (3) To see what your script received, dump the params to the logfile:use Data::Dumper; print STDERR Dumper $cgi->Vars. (4) To de- or encode JSON,use JSONmodule.