Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: CGI HTML Form Data

by haukex (Bishop)
on Apr 20, 2021 at 05:30 UTC ( #11131500=note: print w/replies, xml ) Need Help??


in reply to CGI HTML Form Data

Do you mean something like this?

#!/usr/bin/perl use Mojolicious::Lite -signatures; use File::Replace qw/replace3/; use Mojo::JSON qw/encode_json decode_json/; use Mojo::File; my $DATA_FILE = Mojo::File->new('/path/to/data.json'); helper defaults => sub ($c, $param) { return undef unless -e $DATA_FILE; my $defaults = decode_json( $DATA_FILE->slurp ); return $defaults->{$param}; }; get '/' => sub ($c) { $c->render(template => 'index') } => 'index'; post '/' => sub ($c) { my (undef,$outfh,$repl) = replace3($DATA_FILE); print $outfh encode_json { name => $c->param('name'), }; $repl->finish; $c->render(template => 'index', message => "Form submitted!"); } => 'submit'; app->start; __DATA__ @@ index.html.ep <!DOCTYPE html> <html> <head><title>Hello, World!</title></head> <body> % if ( stash 'message' ) { <p><%= stash 'message' %></p> % } %= form_for submit => ( method=>'post' ) => begin <div> %= label_for name => 'Your Name' %= text_field name => defaults 'name' </div> <div> %= submit_button 'Submit' </div> %= end <p> %= link_to Reset => 'index' </p> </body> </html>

I'm using my module File::Replace to prevent* problems when there are multiple readers, though if there are multiple writers you'll need to use some kind of file locking or similar method to ensure concurrent writes don't step on each other. Or, use a database!

In the past, the same could be achieved with CGI with its CGI::HTML::Functions. However, since those aren't a best practice anymore, I would not recommend it!

Update just in case I made it sound too much like these are the only options: of course there are others, see e.g. here, here, and hippos's post here. Also:

* If atomic renames are supported by the OS and FS. If not, some other technique will be necessary. /Update

Unfortunately people here think every question is stupid, and no longer wish to help other people like they used to do. They only want to downvote questions from people trying to learn and ask for help when something is confusing, instead of trying to help them.

It's a FAQ: Why did I get downvoted?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11131500]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2021-07-30 22:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?