Reputation: 78
This is my first attempt at CGI (I know some Perl) but i'm falling on my face.
I want to enter a form and check it - but the check section isn't seeing the submitted values at all.
I am running this directly as http://example/cgi-bin/formcheck.cgi
- there is no HTML calling this.
I suspect it's running, dropping out the bottom and then running from scratch whenever a button is pressed. I'm not sure though. Here's my code:
#!/usr/bin/perl -w
use strict; # let's tighten things up
use CGI ':standard';
use CGI::Carp qw(fatalsToBrowser);
print header;
print start_html("form check");
print "<h1>form check</h1>\n";
print_questions();
print_checks();
print "<hr>\n";
print end_html;
sub print_questions {
if ( !defined(param('action')) || param('action') eq 'New' ) {
my $p = int(rand(10)); # fix error under strict
my $q = int(rand(10)); # fix error under strict
my $i = 0; # fix error under strict
my @question = ''; # fix error under strict
my @answer = ''; # fix error under strict
$question[$i] = "$p X $q =";
$answer[$i] = $p * $q;
print start_form;
print "$question[$i]";
print textfield(-name=>'response',-default=>'',-size=>3);
print "<p>";
print submit('action','New');
print submit('action','Check');
print end_form;
print "<p>";
param(-name=>'question',-value=>@question);
param(-name=>'answer',-value=>@answer);
print "<hr>\n";
}
}
sub print_checks {
if ( param('action') eq 'Check' ) {
my $errors = 0; # fix error under strict
my $i = 0; # fix error under strict
my @question = param('question'); # fix error under strict
my @answer = param('answer'); # fix error under strict
my @response = param('response'); # fix error under strict
if ( $answer[$i] != $response[$i] ) {
$errors++;
print "<font color=#FF0000>";
} else {
print "<font color=#00FF00>";
}
print "$question[$i] = $answer[$i]";
print "</font>";
print "<p>";
print start_form;
print submit('action','New');
print end_form;
print "<p>";
print "<hr>\n";
if ($errors == 0) {
print "CORRECT!<br>";
} else {
print "NOPE!<br>";
}
}
}
Any help greatly appreciated
Upvotes: 1
Views: 520
Reputation: 78
print textfield(-name=>'response',-default=>'',-size=>3);
print hidden(-name=>'question',-value=>@question); # this fixes my bug
print hidden(-name=>'answer',-value=>@answer); # this fixes my bug
I also have to remove these lines:
param(-name=>'question',-value=>@question);
param(-name=>'answer',-value=>@answer);
Thanks again.
Upvotes: 0
Reputation: 1379
Ok, read your code again:
You set an question and answer parameter, but they do not have any representation in the form. You need a hidden()-field to preserve them.
Upvotes: 1