PHP code delivering search results on the same " /> PHP code delivering search results on the same " /> PHP code delivering search results on the same "/>

Detect that a page has been loaded from form submission

860 Views Asked by At

I have a search form with the following code:

<form id="search_form" action="index.php" method="post">

PHP code delivering search results on the same page is triggered by:

if (isset($_POST['search'])) {

I also have javascript on this page that runs on page load (using addEventListener). Since the page is reloaded with the form submission, the script runs again. This is not desired. Therefore, I would like to detect that the form has been submitted and avoid calling the javascript. I could do it if there was a way for Javascript to detect that the $_POST['search'] has been set.

Another way to put it... I would like the initially loading scripts to be blocked if the page is reload is from a form submission.

How may I achieve my aim using vanilla JS?

1

There are 1 best solutions below

1
Obsidian Age On BEST ANSWER

Just put the desired JavaScript code inside a PHP conditional that only runs when the $_POST value isn't set:

<?php
if (!isset($_POST['search'])) {
?>
  <script>
  // Code to run on initial page load
  </script>
<?php
}
?>

Or, if you prefer to keep it contained within PHP for code clarity:

<?php
if (!isset($_POST['search'])) {
  echo "<script>Code to run on initial page load</script>";
}
?>