4

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;
4
  • 2
    check server access and error log files Commented Oct 6, 2013 at 7:33
  • Thank you very much for your comment. So, does it mean "$cgi = CGI->new; and $id = $cgi->param('data_id');" is not wrong in order to receive data via ajax in jQuery? Commented Oct 6, 2013 at 7:49
  • 6
    (1) Please make your Perl script run under use strict; use warnings → declare your variables. (2) You don't actually print the $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 JSON module. Commented Oct 6, 2013 at 11:21
  • Thank you very much for editing and your advice. I'll modify the code and try it. Commented Oct 7, 2013 at 4:49

2 Answers 2

9

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.