I've created a register page using php, and the the form successfully submits data to the database.
The problem is, I'm trying to prevent client side submission, but I can't get the form to stop submitting, even with nothing in the input fields.
I've even temporarily removed the php, and I'm still having the same issue.
Before I do any further form validation, I need to the form to stop submitting.
it also submits every time and I refresh the page, and I'm not sure why.
Register page with html and php
<?php
require_once "connection.php";
session_start(); //intiate session for current user on site
if (isset($_SESSION["email"]) && isset($_SESSION["password"])) {
header("location: index.php");
}
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, "password");
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//database entry
$create_account = $pdo->prepare("INSERT INTO users (email,password) VALUES (:email, :password)");
$create_account->bindParam(':email', $email);
$create_account->bindParam(':password', $hashed_password);
$create_account->execute();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Food Roulette</title>
<link rel="stylesheet" href="style.css">
</head>
<body >
<div >
<form action="register.php" id="signupForm" method="POST">
<h1 > Register now </h1><br>
<label for="email"> Email Address </label><br>
<input type="email" id="email" name="email"><br>
<label for="password"> Password </label><br>
<input type="password" id="password" name="password"><br>
<button onsubmit="validateRegistrationForm()" name="register_button">Login</button>
</form>
</div>
<script src="app.js"></script>
</body>
</html>
App.js with form validation
function validateRegistrationForm() {
const email = document.getElementById(email);
const password = document.getElementById(password);
form.addEventListener("submit", (e) => {
e.preventDefault();
})
}
CodePudding user response:
Use required fieids so that form will not be submitted empty.
CodePudding user response:
You are registering event listener after the form has been submitted through onsubmit="validateRegistrationForm()"
. You should add event listener outside the validateRegistrationForm function.
Like this:
var form = document.getElementById('signupForm');
form.addEventListener("submit", (e) =>{
const email = document.getElementById(email);
const password = document.getElementById(password);
e.preventDefault();
})
and remove onsubmit from button:
<button name="register_button"> Login </button>