dbonneville
dbonneville

Reputation: 2131

How to create and access a json file using Perl and Javascript

I'm not sure at all if I've approached this correctly. I've created a script in Perl that takes some simple data and creates a simple json formatted output. When I run it local in the shell, I can see the output is correct using a print commmand. The file is called "dates.cgi" and runs locally from the cgi-bin directory. When I try to access the file directly on my local web server, I get a 500 error. It's not a web page, of course, just json output.

I figured that was a web server error. So I set up a standard jquery ajax call, but it too is failing.

Here is the Perl script that prints to terminal correctly:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $dir = '../data';
my $json;
my @dates;

opendir(DIR, $dir) or die $!;

while (my $file = readdir(DIR)) {

    # Use a regular expression to ignore files beginning with a period
    next if ($file =~ m/^\./);

    # pluck out first 8 chars
    my $temp = substr $file, 0, 8;

    # populate array
    push(@dates, $temp);

}
closedir(DIR);

# sort high to low
@dates = sort { $b <=> $a } @dates;
# print Dumper (@dates);

# loop through array and create inner section of json
my $len = @dates;

my $x = 0;
foreach (@dates){

    if ($x < $len-1){
        $json .= "\t{'date':'$_'},\n";  
    } else {
        $json .= "\t{'date':'$_'}\n";
    }

    $x++;

}

# add json header and footer
$json = "{'dates':[\n" . $json;
$json .= "]}";

# print
print "$json\n";

I'm trying to access it this way from a webpage to load the data in:

// load data json
$.ajax({
    url: "cgi-bin/dates.cgi",
    async: false,
    success: function (json) {
        dates = json;
        alert(dates);
        alert("done");
    },
    fail: function () {
        alert("whoops");
    }
    dataType: "json"
});

It's just silently failing. Where do I look next?

Upvotes: 0

Views: 713

Answers (2)

mgamba
mgamba

Reputation: 1199

Check the jquery documentation for .ajax. Looks like they chain done, fail, always, etc instead of specifying inside the first argument

Example,

$.ajax({
  url: "cgi-bin/dates.cgi",
  async: false,
  dataType: "json"
})
.done(function(data) {
  dates = data;
  alert(dates);
  alert("done");
})
.fail(function() {
  alert("whoops");
})
.always(function() {
  alert( "complete" );
});

Upvotes: 0

Asheliahut
Asheliahut

Reputation: 911

You should include the following to your perl file.

use CGI;
my $cgi = new CGI;

Then print proper header for json or just use text plain before anything is printed.

print "Content-Type: application/json", "\n\n";

print "Content-type: text/plain", "\n\n";

Upvotes: 1

Related Questions