Josh Vo
Josh Vo

Reputation: 159

perl cgi talks to javascript

I want to retrieve a csv file from one online database. However, due to some XSS issues, I cant directly use ajax, but need to relay on a perl-cgi file.

I already had a working perl-cgi file that can query the csv file , and write the content of the file into a perl variable called $text. Here are some code snippets:

#!/usr/bin/perl

use strict;
use CGI;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent; 

# construct cgi object
my $q = CGI->new;


# create a post request
my $useragent = LWP::UserAgent->new();  
my $request = POST '.....', [ 
     #something goes here
];
my $response = $useragent->request($request);
my $text = $response->content; 

print $text;

I have some general ideas of what to do next, but not so sure about the details. I will upload this perl-cgi file to the server that hosts my website, to the folder called cgi-bin. I just wonder how can I call that perl-cgi file from javascript, and write back the content of $text into javascript varaiable.

Thanks for the help

Upvotes: 0

Views: 517

Answers (1)

Jared Ng
Jared Ng

Reputation: 5071

Javascript is a client-side language, while Perl is a server-side language. This means that you won't be able to directly read the value of a Perl variable into Javascript.

What you can do is have the Perl script output the results of its operations. Your Javascript then calls this Perl script via AJAX and reads the result.

Here's some pseudocode to illustrate what I mean:

Perl script: csv_worker.cgi

// retrieve csv file into $text as per OP

print "Content-type: text/csv\n\n";
print $text;

Javascript

function request() {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    // Supports newer browsers
    xmlhttp=new XMLHttpRequest();
  } else {
    // Supports older IE versions (IE 5/IE 6)
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("result").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","csv_worker.cgi",true);
  xmlhttp.send();
}

Upvotes: 1

Related Questions