Anonymous
08 Oct, 2017

How To Stop Form Resubmission On Page Refresh?

1 Answer         92552 Views

Admin
08 Oct, 2017

Basically, the general idea is to redirect the user to some other pages after the form submission which would stop the form resubmission on page refresh but if you need to hold the user in the same page after the form is submitted, you can do it in multiple ways.

Unset Form Data 

One way to stop page resubmission on page refresh is to unset the form data after it is submitted so that the variable storing form data becomes empty and wrap up your form processing block of codes to check if the form is empty.

if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
 $data = // processing codes here
 unset $data;
}

This will make $data empty after processing and the first clause would stop form resubmission on page refresh.

Javascript

This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.

<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>

123 Likes         0 Dislike         5 Comments        


Naganath Mali

20 Oct, 2021

On Internet explorer its not working. Any suggestion on IE.

Anonymous

21 Oct, 2021

Seems like your form data is not processed. Make sure the data is processed first. If both the options are not working for your try header redirect php instead with $_SERVER['REFERER'] to get back to the same page.

Reply


abdulkabeerabid

27 Jul, 2022

it really was a magicc.... life saver peice of code :)

Jiwan Thapa

20 Aug, 2022

Glad, it helped.

Reply


Go Kola travel

25 May, 2023

The js-option did the trick. Many Thanks! PS: The unset-option I did not understand how to process code within $data.

Reply


mohi

20 Sep, 2023

The code was great, I tested it in all browsers and it worked

Reply


khadem ul Hasnain

01 Dec, 2023

really Magis

Reply



Leave a comment