Creating and accessing a JSON file with Perl and JavaScript: A step-by-step guide

I'm feeling uncertain about whether or not I have gone about this the right way. I have crafted a Perl script that takes basic data and generates a JSON formatted output. Testing it locally in the shell shows that the output is correct when using a print command. The script, named "dates.cgi," runs from the cgi-bin directory on my local machine without any issues. However, attempting to access the file directly on my local web server results in a 500 error. This file does not serve as a webpage; instead, it outputs JSON data.

I suspected the issue was with the web server, so I set up a standard jQuery AJAX call, but unfortunately, it is also unsuccessful.

Below is the Perl script that successfully prints to the terminal:

#!/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)) {

    # Ignore files starting with a period using a regular expression
    next if ($file =~ m/^\./);

    # Extract the first 8 characters
    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);

# Iterate through the array and create the 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 am attempting to access this data from a webpage to load it:

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

The process is failing silently. What should I investigate next?

Answer №1

Make sure to add the code below to your perl script.

use CGI;
my $cgi = new CGI;

After adding the above code, remember to include the appropriate header for JSON output or simply specify text/plain before outputting anything.

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

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

Answer №2

Take a look at the jQuery .ajax documentation. It seems like they have a chaining method for done, fail, always, etc instead of including them in the initial argument.

For instance,

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the request parameter in my ag-grid to be undefined?

Currently experimenting with the ServerSide RowModel of Ag-Grid in combination with Angular. Planning to add server response later on, but for now focusing on familiarizing myself with the framework. Struggling to retrieve request parameter values from my ...

Capture all URLs containing [...slug] and generate static props only for valid addresses in Next.js

I am utilizing dynamic routes with the fallback:true option to ensure newly created pages are accepted. First, I check if the parameters are true, then I create related props and display the component with those props. In the console, I can observe that Ne ...

Troubles with AJAX comment system validation issues

Having created a webpage that displays articles with a textarea under each article for user comments, I implemented AJAX successfully. The validation also works fine - if the textarea is empty, it will display an error and not submit the comment. However, ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...

Error message "Object reference not set to an instance of an object" occurs in PHP when working with JSON data

Having trouble with a PHP script that is trying to connect to a 3rd Party API with minimal documentation available at here. Despite my efforts in researching and implementing various suggestions, I keep encountering an unfamiliar error from the API. $host ...

If the status of any ticket with is_approved=1 is updated to "2", the field ticket_status will be updated based on the order ID in CodeIgniter

This is the table for requests https://i.sstatic.net/NWT4y.png How can I update the ticket_status field with a value of "2" if at least one of the requests has is_approved=1, based on the orderid? I have attempted the following code, but it is not updat ...

Is it possible to omit specific files from an NPM package during installation?

Is there a way to omit specific files from the list of NPM packages in my package.json? In my unique non-browser environment, every file within the node_modules directory automatically becomes part of the final production package. This means that there is ...

Troubleshooting problem with JSON array value in Petfinder's AJAX request

$(document).ready(function(){ var url = 'http://api.petfinder.com/shelter.getPets?key=99392cbf55ee6b2f9b97ed375eca907d&id=WI22&status=A&output=full&format=json'; $.ajax({ type : 'GET', ...

JSplumb - retrieve a connection targeting a particular endpoint

There are multiple endpoints on my elements. By using the following code snippet, I am able to retrieve all the connections linked to a specific element: // My JSPlumb instance object is named plumber connSet = plumber.getConnections({target:eltID}); Th ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser: eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()"); It will output THIS IS COOL, however, if you run the following: eval("(function() { console ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...

Is it possible in MongoDB to embed a collection within a document of another collection?

Working with Javascript, Node.js, Express, and MongoDB for a web application. Users can create an account with fields for name and last name, but I also need to track completed steps using a boolean value (false for uncompleted, true for completed). Instea ...

The redirect_to_blocks feature in Chatfuel seems to be malfunctioning

I've encountered an issue with my chatfuel JSON API in my node JS application. I am attempting to catch errors and return a message along with a redirect_to_block in order to prompt the user again. The error detection seems to be working fine, as disp ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

Issue with Ajax function's communication with server

Currently, I am working on integrating an uploader script called dropzone.js into my website. Uploading files to the server is functioning correctly, but I am encountering issues with deleting them. Below is the JavaScript code I am using: $(document).rea ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

The ASP.NET Web service is proficient in transmitting data in the form of JSON

A while back, I developed an "ASP.NET Web Service application" using the .NET 3.5 framework. Lately, the number of requests to this application has significantly increased and I am facing bandwidth issues on the server. My initial thought to optimize the ...

"Is there a way to convert a collection of lists into JSON format while

Here is a collection of lists including names, scores, and other data: [['Edan Daniele', '12.61', '5.00', '9.22', '1.50', '60.39', '16.43', '21.60', '2.60', '35 ...

Unveiling the information retrieved from an AJAX request during page load

I've been working on a unique concept for my website. Instead of displaying data from a JSON file upon load, I want it to render only when a specific click event occurs. Initially, I tried using callbacks but soon realized the flaws in that approach. ...