Javascript – How to send a JSON response from a Perl CGI program

javascriptjsonperl

I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file.

I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.

Best Answer

I am doing this in a perl/cgi program.

I use these in the top of my code:

use CGI qw(:standard);
use JSON;

Then I print the json header:

print header('application/json');

which is a content type of:

Content-Type: application/json

And then I print out the JSON like this:

my $json->{"entries"} = \@entries;
my $json_text = to_json($json);
print $json_text;

My javascript call/handles it like this:

   $.ajax({
        type: 'GET',
        url: 'myscript.pl',
        dataType: 'json',
        data: { action: "request", last_ts: lastTimestamp },
        success: function(data){
            lastTs = data.last_mod;
            for (var entryNumber in data.entries) {
                 //Do stuff here
            }
        },
        error: function(){
            alert("Handle Errors here");
        },
        complete: function() {
        }
    });

You don't necessarily have to use the JSON library if you don't want to install it, you could print straight JSON formatted text, but it makes converting perl objects to JSON prety easy.