Home > database >  Can't prevent page from refreshing
Can't prevent page from refreshing

Time:06-30

I got some very helpful suggestions from a post a couple days ago (thank you to all who responded) and a new issue has come up that I can't seem to solve.

I have a php file that is a registration form posting data to a MySQL database. The form posts correctly, and after posting, the html updates via a JS function. But the update doesn't stay on the page long enough to be read and the page refreshes.

Here is the code, and below that a list of all the things I have tried to fix the problem without any success:

<!DOCTYPE html>
<?php 

if ($_SERVER["REQUEST_METHOD"] == "POST"){


$dbServername = "mysite.com";
$dbUsername = "myusername";
$dbPassword = "12345";
$dbName = "dbname";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

$firstname   = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname    = mysqli_real_escape_string($conn, $_POST['lastname']);

$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$firstname', '$lastname')";

mysqli_query($conn, $sql);
mysqli_close($conn);

unset($_POST);

header('Location:'.$_SERVER['PHP_SELF']);
}


?>


<html lang="en">
  
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="style/styles.css" />
    <!--<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>-->
    <link rel="shortcut icon" href="#" />
    <meta
      name="description"
      content="content"
    />

    <title>Site | Page</title>
  </head>

  <body>
    <nav >
      <div >
        <div >
          <div >
            <span
              ><a href="index.html" 
                >Company </a
              ></span
            >
            <span 
              >Text</span
            >
          </div>
          <div >
            <span 
              ><a href="index.html" >Home</a>
            </span>
            <span >
              <a href="about.html" >About</a>
            </span>
            <span 
              ><a href="search.html" >Search</a></span
            >
            <span 
              ><a href="contact.html" >Contact</a></span
            >

            <span >
              <a href="../spanish/inicio-esp.html" >Español</a>
            </span>
            <span 
              ><a href="../portuguese/inicio-port.html" 
                >Português</a
              ></span
            >
          </div>
        </div>
      </div>
    </nav>

    <div id="registrationOne">
    <div >


<form name="regForm" method="post" action=<?php echo $_SERVER['PHP_SELF'];?> onsubmit="thankReg();">
<div >
  <div >
              <label for="">First Name:</label>
              <input name="firstname" type="text"  />
            </div>
            <div >
              <label for="">Last Name:</label>
              <input name="lastname" type="text"  />
            </div>

</div>
<button
            name="submitButton"
            type="submit"
            
            id="registrationTwo"
            
            >
            Register
          </button>

</form>
        
    </div>
    </div>
  
  </body>
  <script src="script/index.js"></script>
  
  </html>

And then the JS:

function validateRegForm(event) {
  let valid = true;
  let first = document.forms["regForm"]["firstname"].value;
  let last = document.forms["regForm"]["lastname"].value;

  if (first.length < 2) {
    alert("Please enter a first name at least of at least two characters");
    valid = false;
  } else if (last.length < 2) {
    alert("Please enter a last name at least of at least two characters");
    valid = false;
  } else {
    document.forms["regForm"].submit();
  }
  if (!valid) {
    event.preventDefault();
  }
}

let regClick = document.getElementById("registrationTwo");
regClick.addEventListener("click", validateRegForm);

function thankReg() {
  let regOneElement = document.getElementById("registrationOne");
  regOneElement.innerHTML = `<div >
<div >
<h2 >Thank you for registering with Pro.Social.<br /><br />Please check your email for your unique search link to get started. <br /><br />If you do not receive an email from us in the next few minutes, please contact us via the Contact page.</h2>
</div>
</div>`;
}

Here are all the things I have tried but none has worked:

  • Adding return false; to end of thankReg()
  • Adding onsubmit="return thankReg();" to form instead of just onsubmit="thankReg();"
  • Adding return false; to thankReg() and onsubmit="return thankReg(); to form
  • Adding event.preventDefault() to end of thankReg()
  • Nesting thankReg() in validateRegForm() and calling return thankReg()
  • Nesting thankReg() in validateRegForm() and calling thankReg()
  • Adding a second event listener that calls thankReg()
  • Adding location.href = "https://www.anewpage.com"; to end of validateRegForm()
  • Adding window.location.replace("http://www.anewpage.com"); to end of validateRegForm()
  • Adding if (valid) {window.location.replace("https://www.prosocial.online/about.html");} to end of validateRegForm()

Any suggestions are appreciated! Thanks again.

CodePudding user response:

Your thankReg() JavaScript function runs during the HTML form's onsubmit event. That means it runs in the browser before the form has been submitted to the server. A moment later of course, the form is submitted which causes a HTTP request to the server, so the browser clears the current page in anticipation of a new response to that request coming back from the server.

To allow the message to persist longer, you need to make PHP trigger the message to be displayed after the form has been submitted, so that it doesn't a) appear prematurely before the form has actually succeeded, and b) get immediately removed.

Since you're issuing a redirect header, this task needs to happen when the redirected page is loaded, not in the immediate response to the form submission (which the browser will never display). So adding a query parameter into that redirect URL is a good way to do it - that can be used to indicate that the thankyou message needs to be shown.

Remove the thankReg() function and the onsubmit handler which triggers it. Then, try something like this:

Amend

header('Location:'.$_SERVER['PHP_SELF']);

to

header('Location:'.$_SERVER['PHP_SELF']."?msg=thanks");

Then, further down the page:

<div id="registrationOne">
<?php
if (isset($_GET["msg"]) && $_GET["msg"] == "thanks") {
?>
  <div >
    <div >
      <h2 >Thank you for registering with Pro.Social.<br /><br />Please check your email for your unique search link to get started. <br /><br />If you do not receive an email from us in the next few minutes, please contact us via the Contact page.</h2>
    </div>
  </div>
<?
}
?>

CodePudding user response:

You can't both handle the form with php and js at the same time.

You need a page reload to handle it with PHP, while javascript is gonna lose all infos if you do so.

what you can do is use XMLHttpRequest to send the data to your back end, and update the page when you get the response

  • Related