As I didnt find out how to do this with javascript, I used php sleep() -function before redirecting user to another page. Naturally preventDefault needed to be removed as it blocked the submit action. This solution solves the use case for me: Just to display user a message that the page is loading.
How to use blockUI with setTimeout and preventDefault on form submit?
-
30-06-2022 - |
Question
Here is shortly what I am doing and why:
- I have a form, which is preprocessed with different scripts according user input
- Usually script is executed in less than seconds, however one script may take around 10 seconds depending on server load etc.
- Now I want to implement this "popup" containing: "Please wait while..." Im using blockUI for that - simple plugin for implementing this.
- However, blockUI for fast script execution is quite stupid, as user will only see the popup flashing on the screen.
- Therefore I want to set timeout for it, like 1000ms, so that blockUI is displayed even though form would have been already completed
- So far I've tried quite many things, now I basically use preventDefault to cancel form submit for the setTimeout, but Im unable to complete the form submit after that.
Edit: Found out, that as javascript is asynchronous language, without preventDefault (stop form submitting) setTimeout never launches and action returns true straight away.
<form method="post" name="my_form" id="my_form" enctype="multipart/form-data">
<input type="submit" name="my_submit" id="my_submit" value="Submit" />
<div id="form_loading_message" style="display:none;">
<h1>Please wait, page is loading...</h1>
</div>
</form>
$('#my_submit').click(function(event) {
$.blockUI({
message: $('#form_loading_message')
});
var form = $('#my_form');
event.preventDefault();
setTimeout(function () {
form.unbind('submit').submit();
$.unblockUI();
}, 1000);
});
If you have better idea how to do this, please, I'm open for other suggestions aswell...
Solution 2
OTHER TIPS
Not familiar with blockUI, but... Here's how I would do it:
<html>
<head>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#my_submit').click(function() {
$('#form_loading_message').show();
setTimeout('submitForm()', 1000);
});
});
function submitForm(){
$('#my_form').submit();
}
</script>
</head>
<body>
<form method="post" name="my_form" id="my_form" action="google.com" enctype="multipart/form-data">
<input type="button" name="my_submit" id="my_submit" value="Submit" />
<div id="form_loading_message" style="display:none;">
<h1>Please wait, page is loading...</h1>
</div>
</form>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow