Here's one way, with AJAX:
Update: To clarify, this mainly shows how to do the form submission asynchronously - you can always modify this code so that it, for example, redirects to a different page when the form submission is complete, to show a "spinner" image instead of the "Submitting" message, and so on. /Update
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
$c->render(template => 'index');
} => 'index';
post '/submit' => sub ($c) {
$c->render_later;
Mojo::IOLoop->timer(10 => sub { # simulate long process
if ( $c->param('foo') =~ /foo/i ) {
$c->render(json => { ok=>1, message=>"All good" });
}
else {
$c->render(json => { ok=>0, message=>"Bad foo value" });
}
});
} => 'formsubmit';
app->start;
__DATA__
@@ layouts/main.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
%= content
</body>
</html>
@@ index.html.ep
% layout 'main', title => 'Hello, World!';
<div>
%= form_for formsubmit => ( method=>'post', id=>'myform' ) => begin
<div>
%= label_for foo => 'Foo'
%= text_field foo => ( placeholder=>"Foo", required=>'required' )
(must contain "foo")
</div><div>
%= label_for bar => 'Bar'
%= text_field bar => ( placeholder=>"Bar" )
</div><div>
%= submit_button 'Login'
<span id="formmessage"></span>
</div>
%= end
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
$(function () {
$('#myform').on('submit', function (e) {
e.preventDefault();
var thedata = $('#myform').serialize(); // before disabling!
$("#formmessage").text("Submitting, please wait...");
$("#myform :input").prop("disabled", true);
$.ajax({ type: 'post', url: '<%= url_for 'formsubmit' %>',
data: thedata, timeout: 120*1000 })
.done( function( data ) {
if (data.ok) {
alert("Form was submitted: "+data.message);
}
else {
alert("Problem with submission: "+data.message);
}
})
.fail( function( jqXHR, textStatus, errorThrown ) {
alert("Form submission error: "+textStatus
+" / "+jqXHR.status+" "+errorThrown);
})
.always( function () {
$("#formmessage").text("");
$("#myform :input").prop("disabled", false);
});
});
});
</script>
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.