So i fill textarea, press submit and... i get raw json response in my browser.
Question is:
How do i separate "api" from "frontend" and made them pass data between each other in order to
- have nice form
Note you can seprate your API from the frontend purely on the Perl level. Mojolicious includes content negotiation, as I show in the following example (run it e.g. via morbo script.pl). Note how POST and GET just work, including http://127.0.0.1:3000/myform?foo=helloworld&format=json and http://127.0.0.1:3000/myform.txt?foo=blahblah.
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
any '/' => sub ($c) { $c->redirect_to('/myform.html') };
sub my_api_do_thing ($arg) { # could/should be in a module!
return $arg =~ s/[aeiou]//gr;
}
any '/myform' => sub ($c) {
if ( defined $c->param('foo') ) { # if the form was submitted
$c->stash( returnval => my_api_do_thing( $c->param('foo') ) );
}
$c->respond_to(
json => { json => { retval => $c->stash('returnval') } },
txt => { text => $c->stash('returnval') },
html => { template => 'myform' },
);
};
app->start;
__DATA__
@@ myform.html.ep
% layout 'main', title => 'Hello, World!';
<div>
% if ( stash 'returnval' ) {
<div>
Return value: <%= stash 'returnval' %>
</div>
% }
%= form_for myform => ( method=>'post' ) => begin
<div>
%= label_for foo => 'Foo'
%= text_field foo=>'Foobar?'
</div>
<div>
%= radio_button format => 'html', id=>'format_html', checked => un
+def
%= label_for format_html => 'HTML'
%= radio_button format => 'json', id=>'format_json'
%= label_for format_json => 'JSON'
</div>
<div>
%= submit_button
</div>
%= end
</div>
@@ layouts/main.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
%= content
</body>
</html>