D.Karthikeyan D.Karthikeyan - 2 months ago 8
Perl Question

CGI: How to increment Perl variable inside JavaScript

In perl cgi script, I need to increment perl array variable index inside script tag to add each value in array variable in each html

<p id="para1"> <p id="para2"> <p id="para3">
<p id="paran">
one by one.

Here, number of
tags and length of perl array variable is same.

I tried JavaScript increment variable for perl array variable index ,but its not working.

Is there any other way possible to do this?

Sample code:

use CGI;
print "content-type:text/html\n\n";
my @jslabel = ('1','2','3');
print <<EOF;
<p id="para0"> hi </p>
<p id="para1"> hi </p>
<p id="para2"> hi </p>
for(var i=0;i<3;i++)
document.getElementById("para"+i).innerHTML =$jslabel[i];

Desired RESULT web page should show like this:


But, the outcome for the given code:


How to achieve the Desired RESULT?

Thanks in advance for the help.


You may be able to solve the problem by JSON encoding your perl data, and then reading the data from that with your javascript.

#! /usr/bin/perl

use strict;
use warnings 'all';

use CGI;
use JSON;

# note that JSON expects array references
my $jslabel = [ 1, 2, 3 ];

# if we're using CGI, we may as well use it's functions
my $cgi = CGI->new();
print $cgi->header('text/html');

# convert our array to JSON
my $data = to_json($jslabel);

my $html = qq:
        <title>A title is always nice</title>

        <!-- javascript is best served inside the <header> -->
             <!-- we're inserting the data here because of use of qq// -->
             var jslabel = $data
             for(var i=0;i<3;i++) {
                 document.getElementById("para"+i).innerHTML = jslabel[i];
        <p id="para0"></p>
        <p id="para1"></p>
        <p id="para2"></p>

print $html;

However I'd also point that html documents are better served out of "template files" and data inserted to them via modules that provide that functionality. Good examples of modules from CPAN that provide that functionality are HTML::Template or Template::Toolkit. However this is beyond the scope of the question.

Another alternative is to use some form of AJAX mechanism to fetch the results "live" data from a seperate CGI script and populate from the returned results (that is more of a "Web 2.0" way of approaching things).