So I have a button in my CGI Perl. On clicking that button I need to assign a action in perl CGI, on clicking that button a New text-area should open with specified width in the same page with a submit button. Please help me on how I can proceed. Here is the code which is not really working for me. On clicking on submit button, I what to email the message to a email id
Here I print the button
print button('email',"email me","reqts()");
Here is the opentextarea subroutine
sub reqts {
print "<p><em>Enter your Message here</em><br>";
print textarea(-name=>'Comments',
-rows=>10,
-columns=>50);
print submit('Action','Send');
}
On clicking this button the subroutine is not getting called.
This button is on a html form in another subroutine
sub actions {
print
start_html(),
start_form(-action => 'com.pl'),
submit(-name => 'submit', -value => 'View com.pl'),
end_form,
print button('email',"email me","reqts()"), # this is the button
start_form(-action => 'about.pl'),
submit(-name => 'submit', -value => 'About Us');
end_form,
end_html;
}
The onClick attribute (the third argument to button) should be a JavaScript function, not Perl function. You should study how CGI and webpages work.
Related
I am just doing a testing using WWW::Mechanize module on Facebook, when I try to run the code below, it return me an error
Can't call method "header" on an undefined value at C:/Strawberry/perl/vendor/lib/WWW/Mechanize.pm line 2566.
#!/usr/bin/perl -w
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
# Connect to server
$mech->get( "https://www.facebook.com" );
$mech->success or die $mech->response->status_line;
# Log into server
$mech->field('email', 'xxx#xxx.com');
$mech->field('pass', 'xxxxxxx');
$mech->click_button(value => 'Log In');
Your page is opening in some other language other than English. That's why you are getting that error. If you will open the page in English forcefully then the error will disappear. Try below address:
$mech->get( "https://en-gb.facebook.com/" );
or, you may click directly on instance of HTML::Form::SubmitInput obtained using this:
$mech->current_form()->find_input( undef, 'submit');
or, as there is only one click button in the form you can use click with no arguments.
$mech->click()
or as suggested by #Borodin you can directly use(as the email and password field aren't translated):
$mech->submit_form( with_fields => {
email => 'xxx#xxx.com',
pass => 'xxxxxxx'
}
);
I am rewriting this question to make it specific:
The requirement of the webpage is
Read the rules from a file and populate the text-boxes when the webpage is loaded
An add button to add additional textboxes
A save button to save the rules ( including the additionally added ones back to the file)
A delete button to delete the textboxes which are checked so that the rules in them are not stored back to the file.
My approach :
Use "read_rules" submodule to read the rules from the webpage and if its non empty then use "rule" submodule to print them on webpage. Here each line in the file is read and split with spaces and put in a array of hash and prints on the webpage ("rules" module).
When the sumit button is pressed sumodule "save_rules" is called which saves the rules. The reverse way as in read_rules.
An add button will add additional text areas.
A delete button should delete the text areas which are checked and reload the page so when the page is reloaded the text areas which were checked wont appear and hence when save button is pressed they are not saved in file ??? (this I have to implement)
The code blocks of each submodule I have mentioned are below.
This submodule to print the text boxes and checkbox:
sub rule {
my($num,$rule) = #_;
return join "\n",
"<tr><td><br>",
hidden(
-name => "idx$num",
-default => $rule->{idx},
),
checkbox(
-name => "checkbox$num",
-label => "",
-value => "on",
),
"<td>",
textfield(
-name => "repository$num",
-size => 30,
-default => $rule->{'repo'},
),
"<td>",
textfield(
-name => "branch$num",
-size => 30,
-default => $rule->{'branch'},
),
"<td>",
textfield(
-name => "file$num",
-size => 30,
-default => $rule->{'file'},
),
}
This sumodule to read the rules from file
sub read_rules {
my $rule;
#rules = ..# read the rules from a file, each line is read as an element of an array
for $rule (#rules){
my $rec = {};
($re,$br,$fi) = split (' ', $rule);
$rec->{'repo'} = $re;
$rec->{'branch'} = $br;
$rec->{'file'} = $fi;
push #config, $rec;
}
}
The sumodule to save the rule on webpage ( in text area) back to the file
sub save_rules {
for ($i = 1; param("repository$i"); $i++) {
$repo1 = param("repository$i");
$branch1 = param("branch$i");
$file1 = param("file$i");
my $record = {};
# save back $myrec->{'repo1'} $myrec->{'branch1'} $myrec->{'file1'} to file
}
}
Main function
print start_form();
read_rules();
Delete_all();
my $i = 0;
if (#config) {
foreach $conf (#config) {
$i++;
print rule($i,$conf);
}
print $table_header_string;
if (param("action") eq "Add") {
print(br,rule(++$i),hr);
}
print p( submit (-name => "action" , -value => "Add"));
print p( submit (-name => "action" , -value => "Save"));
print p( submit (-name => "action" , -value => "Delete"));
print end_form();
exit 0;
Delete_rule submodule below has to be coded !!
sub delete_rule(){
#................
}
I would appreciate if some one tells me how to use javascript in cgi so I don't have to load webpage every time a button is pressed.
Edited to address more specific question
Given that you don't want to reload the page each time the button is clicked, you are going to want to use JavaScript to do this. I'll explain how here, and you can click here to see a working jsfiddle example.
<!doctype html>
<html>
<head>
<title>Remove Element On Button Click</title>
</head>
<body>
<input type="text" id="myTextBox" value="something here">
<input type="button" id="btnDelete">
</body>
<script>
document.getElementById('btnDelete').onclick = function ()
{
var textbox = document.getElementById('myTextBox');
textbox.parentNode.removeChild(textbox);
}
</script>
</html>
Notice that I changed the type of input element from submit to button. This automatically prevents the page from reloading.
If you absolutely must use a submit input element (and the jsFiddle example does), you can prevent form submission by changing the Javascript thusly:
document.getElementById('btnDelete').onclick = function (evt)
{
if (!evt) var evt = window.event;
if (evt.preventDefault) { evt.preventDefault(); } else { evt.returnValue = false; }
var textbox = document.getElementById('myTextBox');
textbox.parentNode.removeChild(textbox);
}
The JavaScript can be placed in an external file, if prefered. It's placed at the end of the HTML here so as to ensure that the DOM had fully loaded (and hence the button was available in the DOM) prior to attempting to attach an event handler.
It was unclear to me whether there would be one or multiple 'Delete' buttons in your output, or if there would be one or multiple fields that would need to be removed, but this should point you in the right direction.
This is a pure JavaScript solution. As #vol7ron correctly pointed out, there are JavaScript frameworks, like jQuery, that could be used to do this as well, and if you are already using such a framework it would be advantageous to utilize it, however no such framework is in anyway required to accomplish this.
I'm writing a script that selects a size and adds the product to cart here is where it is
http://store.nike.com/us/en_us/pd/free-4-flyknit-running-shoe/pid-1064825/pgid-1481072
use WWW::Mechanize::Firefox;
$mech = WWW::Mechanize::Firefox->new();
my $tconike = "http://store.nike.com/us/en_us/pd/free-4-flyknit-running-shoe/pid-1064825/pgid-1481072";
$mech->get($tconike);
print $mech->uri();
$mech->submit_form(
form_number=> 2,
fields => {
skuAndSize => $shoesize,
click => "ADD TO CART",
}
);
But here is the output
Uncaught exception from user code:
No form found to submit. at nikecartstandalone.pl line 25
at C:/Users/Brett/Documents/brett/Perl/perl/site/lib/WWW/Mechanize/Firefox.pm l
ine 2162
WWW::Mechanize::Firefox::signal_condition('WWW::Mechanize::Firefox=HASH(
0x2a54888)', 'No form found to submit.') called at C:/Users/Brett/Documents/bret
t/Perl/perl/site/lib/WWW/Mechanize/Firefox.pm line 3649
WWW::Mechanize::Firefox::submit_form('WWW::Mechanize::Firefox=HASH(0x2a5
4888)', 'form_number', 2, 'fields', 'HASH(0x3501328)') called at nikecartstandal
one.pl line 25
Anyone know what I did wrong, is it because I should have used something besisdes submit_form or is it something else?
As the error says it's not able to find the form, so try submitting form with with_fields where you can specify the fields which are there in the form you are going to submit, that'll be easier to search and submit.
Eg: $mech->form_with_fields('username');
will select the form that contain a field named username.
Using Perl Tkx, I want to get some input from the user, close the window, and maybe do it again later. For user input, I'm just displaying some buttons, and the user gets to click on one of them. Here's what I have now:
sub prompt_user {
my $answer;
my $mw = Tkx::widget->new("."); ## the main window is unavailable the second time
$mw->g_wm_title("Window Title"); ## line 40
$mw->g_wm_minsize(300, 200);
my $label = $mw->new_label( -text => "Question to the user?");
$label->g_pack( -padx => 10, -pady => 10);
my $button1 = $mw->new_button(
-text => "Option One",
-command => sub { $answer = 0; $mw->g_destroy; },
);
$button1->g_pack( -padx => 10, -pady => 10);
my $button2 = $mw->new_button(
-text => "Option Two",
-command => sub { $answer = 1; $mw->g_destroy; },
);
$button2->g_pack( -padx => 10, -pady => 10);
Tkx::MainLoop(); ## This blocks until the main window is killed
return $answer;
}
So the user clicks on one of the buttons, the window closes, prompt_user() returns 0 or 1 (depending on which button the user clicked), and execution continues. Until I try to prompt the user again. Then I get an error:
can't invoke "wm" command: application has been destroyed at MyFile.pm line 40
I just want a way to put up a bunch of buttons, let the user click one, wait to see which one is clicked, and maybe do it again later. Is there a way I can wait for a response to the button click without destroying the main window? Maybe create a subwindow?
I'm new to using Tkx, and googling shows lots of simple examples like the above code (using MainLoop/g_destroy), but I couldn't find any examples of recreating windows. I did see stuff about a Dialog Box or Message Box, but those won't suit my needs. I want to put text on the buttons, and use an arbitrary number of buttons (so I don't want to be limited to yes/no/cancel, and only have 3 options).
Update
Here's what I was able to use
# hide the main window, since I'm not using it
my $mw = Tkx::widget->new(".");
$mw->g_wm_withdraw();
# function to prompt the user to answer a question
# displays an arbitrary number of answers, each on its own button
sub prompt {
my $prompt = shift;
my $list_of_answers = shift;
# Note: the window name doesn't matter, as long as it's './something'
my $answer = Tkx::tk___dialog( "./mywindowpath", # window name
"Prompt", # window title
$prompt, # text to display
undef, # tk bmp library icon
undef, # default button
#$list_of_answers); # list of strings to use as buttons
return $answer;
}
# use the button to ask a question
my $index = prompt("Who was the best captain?",
[ "Kirk", "Picard", "Cisco", "Janeway", "Archer" ] );
I'm not really familiar with Tkx but Tk doesn't really work well that way. In general Tk applications are asynchronous. You should re-write your application in term of callbacks (kind of like javascript).
Basically, this kind of logic:
sub do_something {
perform_some_action();
my $result = prompt_user();
perform_some_other_action($result);
}
should be re-written to something like:
sub do_something {
perform_some_action();
prompt_user(perform_some_other_action);
}
Your program should basically not have a main loop. Instead the call to Tkx::MainLoop at the end of your program becomes the main loop and you should do all processing by handling events.
Having said that, there are some mechanisms available that emulates blocking. Read the documantation for vwait. Though, I think even that requires a running Tkx::MainLoop so it does not necessarily avoid refactoring your whole program.
On the question of how to create and destroy windows there are two solutions:
Use the main window (.) but don't destroy it at the end. Instead hide it and destroy all its children. You can then later reuse . by unhiding it.
Hide . and don't use it. Instead create other windows (toplevels) and use them. Since toplevels are children of . they are safe to destroy without screwing up Tk.
In my Perl/Tk script I have opened two windows. After a specific button click I want to close one of them. How can I do that? Here's what I have so far:
$main = new MainWindow;
$sidebar = $main->Frame(-relief => "raised",
-borderwidth => 2)
->pack (-side=>"left" ,
-anchor => "nw",
-fill => "y");
$Button1 = $sidebar -> Button (-text=>"Open\nNetlist",
-command=> \&GUI_OPEN_NETLIST)
->pack(-fill=>"x");
MainLoop;
sub GUI_OPEN_NETLIST
{
$component_dialog = new MainWindow;
$Button = $component_dialog -> Button (-text=>"Open\nNetlist",
-command=> **close new window**)
->pack(-fill=>"x");
MainLoop;
}
The simplist way is to call $component_dialog->destroy in the buttons -command callback. This has the disadvantage that if you want to redisplay the window later you have to recreate it.
The withdraw method will hide the window without destroying it so you can redisplay it later if you need to. This will save you some time when the button is pressed. The classes Dialog and DialogBox do this for you automatically when one of their buttons is pressed. If you need a window that behaves like a traditional dialog they can a much simpler option that building your own.
Also except in unusual cases you shouldn't need more than one call to MainLoop. When your callback GUI_OPEN_NETLIST returns the MainLoop will resume, explicitly calling MainLoop will likely lead to odd bugs later.
I think this is close to what your looking for, I haven't tested it though.
use strict;
use warnings;
my $main = new MainWindow;
my $sidebar = $main->Frame(-relief => "raised",
-borderwidth => 2)
->pack (-side=>"left" ,
-anchor => "nw",
-fill => "y");
my $Button1 = $sidebar -> Button (-text=>"Open\nNetlist",
-command=> \&GUI_OPEN_NETLIST)
->pack(-fill=>"x");
my $component_dialog = $main->Dialog( -buttons => [ 'Close' ], );
MainLoop;
sub GUI_OPEN_NETLIST
{
$component_dialog->Show();
}
If you don't want a dialog you should consider if you want to create a second MainWindow or create a Toplevel window dependant on your existing MainWindow.
A Toplevel will close automaticaly when it's MainWindow is closed, a second MainWindow will stay open after the other MainWindow is closed.