Given is a form that is followed by a confirmation page where you have to confirm you entered data of previous form. Now if the user refreshes this recapitulation page, the data form the previous form reposts. Is there a way to prevent that in JavaScript?
I know its not a ideal solution, it should happen on the server side. But i have no choice in this case.
Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
You can prevent form resubmission via a session variable. Yes we can use microtime() as well as time() also instead of rand() , whatever function or variable that gives different value we can use it. BUT make sure that you set that value to SESSION variable.
After Form submission, when the Refresh Button in the Browser is clicked or the F5 key is pressed, a warning popup comes up which warns against Form resubmission. The solution is very simple, either the page must be redirected to itself or to some other page in order to avoid this particular behavior.
We can use Post/Redirect/Get (PRG) pattern to solve the issue of multiple submission of same data. It works as follows: First time when a user submits a form to server by POST or GET method, then we update the state in application database. Then we send a redirect response to send reply to client.
You CAN do this in JavaScript using history.replaceState(null, document.title, location.href);
to clear the post data. I've tested this on an MVC related table editor (that I created myself) that posts to the same url and it works great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With