Home > database >  Form not submitting and innerhtml not updating
Form not submitting and innerhtml not updating

Time:06-26

I am trying to set up a website registration page that will post to my MySQL database

I have the following file, mypage.php, coded as follows

<!DOCTYPE html>
<?php 

            $dbServername = "mysite.com";
            $dbUsername = "username";
            $dbPassword = "12345";
            $dbName = "databasename";

            $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if($conn){ echo "Connected!";}     

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $firstname   = mysqli_real_escape_string($_POST['firstname']);
    $lastname    = mysqli_real_escape_string($_POST['lastname']);
}
          

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

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


<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 here"
    />

    <title>Title | Pagename</title>
  </head>

  <body>
    <nav >
      <div >
        <div >
          <div >
            <span
              ><a href="index.html" 
                >Name </a
              ></span
            >
            <span 
              >Some 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'];?>>
<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 the following javascript file, index.js, coded as follows

function validateRegForm(event) {
  event.preventDefault();

  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");
    return false;
  } else if (last.length < 2) {
    alert("Please enter a last name at least of at least two characters");
    return false;
  } else {
    return true;
  }
}

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


function thankReg() {
  if (validateRegForm() === true) {
    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>`;
  }
}
thankReg();

When I load the page, it shows "Connected!" at the top, so the connection is ok. The form validation works as expected, but when I click on the "Register" button, nothing happens (i.e., the innerhtml doesn't change and nothing is posted to the MySQL database). However, if I refresh the page, blank rows appear in the database.

Could someone please advise?

Many thanks in advance.

CodePudding user response:

event.preventDefault(); prevents the form from submitting. You should only do this if validation fails.

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;
  }
  if (!valid) {
    event.preventDefault();
  }
}

You could avoid this by simply putting minlength="2" in your <input> elements.

You shouldn't call validateRegForm() from thankReg(), since there's no event to pass as the argument. I'm not sure why you're calling this at top-level in the first place, since that runs before the form is submitted.

CodePudding user response:

let's see if I can be of help for you.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//enter your code for connecting to the DB after you have verified that there are POSTS


$dbServername = "mysite.com";
$dbUsername = "username";
$dbPassword = "12345";
$dbName = "databasename";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if($conn){ echo "Connected!";}

//mysqli_real_escape_string requires knowing what kind of carset the database is using so it should be put like this.

$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);
}
?>
  • Related