user1684636
user1684636

Reputation: 91

Why can't I return a json object from a Perl script?

I am doing a little project that uses jQuery,AJAX,JSON,and Perl. On the backend, I am using Perl and its CGI module to return a JSON ojbect.

#!/usr/software/bin/perl5.8.8

use strict;
use warnings;
use CGI qw(:standard);
use JSON;

print header('application/json');
my $json;
# eventually the json that will be returned will based on params,
# for now using this list as example.
$json->{"entries"} = [qw(green blue yellow red pink)];
my $json_text = to_json($json);
print $json_text;

I was able to write the above script, with the help of How can I send a JSON response from a Perl CGI program?

This script is called using jQuery's get:

jQuery.getJSON("script.pl?something=whatever", function(data, status) {
    console.log(data);
    console.log(status);
},"json").error(function(jqXhr, textStatus, error) {
    /* I am always ending up here. */
    console.log(jqXhr);
    console.log("ERROR: " + textStatus + ", " + error);
});

From the above jQuery call, I was expecting to get a JSON object back, but instead I get the entire Perl script. I know that my content type is set correctly, because I get this back when I execute the script from the command line:

Content-Type: application/json

Can someone please help me figure this out. Thank you.

Upvotes: 0

Views: 1511

Answers (2)

Matt Simerson
Matt Simerson

Reputation: 1115

As the others pointed out, you need to configure your web server to run the perl script as a CGI. If your web server is Apache, and your CGI is named 'json.cgi', then you'd add a line like this to your httpd.conf:

AddHandler cgi-script .cgi

Since you are using jQuery, then you should read this little nugget from the JSON pod, under the heading to_json:

   If you want to write a modern perl code which communicates to outer
   world, you should use "encode_json" (supposed that JSON data are
   encoded in UTF-8).

Use 'perldoc JSON' for the rest of the story.

Upvotes: 0

Quentin
Quentin

Reputation: 943537

instead I get the entire Perl script

The server isn't running the Perl script, it is serving it up as plain text.

You need to read the manual for your server to find out how to configure it for CGI.

Upvotes: 4

Related Questions