0

When I try to run this script:

<form class="form-inline" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
    <button type="submit" name="buttonSubmit" class="btn btn-default">Submit</button>
</form>
<?php
  if (isset($_POST['buttonSubmit'])) {
    unset($_POST['buttonSubmit']);
    echo "<script>alert(".isset($_POST['buttonSubmit']).")</script>";
    echo "<script>location.reload(true);</script>";
  }
?>

As a result, the page is refreshing in an infinite loop.

What is the reason?

How do I refresh my website only once?

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Lukasz Re
  • 79
  • 1
  • 11

2 Answers2

1

When you use location.reload(true);, you do the same, programmatically, as clicking on the browsers "Refresh/Reload" button.

This will generate yet another "submit", over and over, hence always make the statement isset($_POST['buttonSubmit']) be true.

Here are a couple solutions:

  • location.href = 'page-to-load';

  • location.assign('page-to-load');

  • location.replace('page-to-load');

    The Location.replace() method replaces the current resource, and after that the current page will not be saved in session History, meaning the user won't be able to use the back button either, to navigate to it and cause a repeated "submit", which normally will occur.

Note, if the 'page-to-load' is the same being already loaded, you can use location.href, e.g.

location.replace(location.href);

Yet another way would be, instead of rely on a client side script, to do a response redirect upon a form submittion, server side.

Asons
  • 84,923
  • 12
  • 110
  • 165
1

This helped me:

Change location.reload(true); to window.location.href = '';

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Lukasz Re
  • 79
  • 1
  • 11