I have a problem. I don't know why when I did run the HTML and javascript only (without PHP part), the validation works really well. However, when I did run the PHP with the HTML and JavaScript, the validation doesn't work. For example, when the username is 123john (everything else such as password, name,... met the requirements) which is not allowed. The form still submitted successfully (I did check the MySQL database and the user 123john is there). Can someone help me with this? Thank you for your help.
The original code structure is the PHP and HTML are in the same file, only the JavaScript is on a separate file.
<?php
session_start();
require 'connect.php';
if(isset($_POST['register'])){
$username = !empty($_POST['user_name']) ? trim($_POST['user_name']) : null;
$pass = !empty($_POST['pass']) ? trim($_POST['pass']) : null;
$firstName = !empty($_POST['first_name']) ? trim($_POST['first_name']) : null;
$lastName = !empty($_POST['last_name']) ? trim($_POST['last_name']) : null;
$collegeName = !empty($_POST['uni']) ? trim($_POST['uni']) : null;
$majorName = !empty($_POST['major']) ? trim($_POST['major']) : null;
$sql = "SELECT COUNT(user_name) AS num FROM users WHERE user_name = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('Username existed');
}
$sql = "INSERT INTO users (user_name, pass, first_name, last_name, uni, major) VALUES (:username, :password, :first_name, :last_name, :uni, :major)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $pass);
$stmt->bindValue(':first_name', $firstName);
$stmt->bindValue(':last_name', $lastName);
$stmt->bindValue(':uni', $collegeName);
$stmt->bindValue(':major', $majorName);
$result = $stmt->execute();
if($result){
echo 'Thank you for registering with our website.';
}
}
?>
var check_form=document.getElementById("registration");
var pattern=/^[a-zA-Z\s]+$/;
var patternUsername=/^[A-Za-z]\w*$/;
function check(event){
var userName=document.getElementById("username");
var passWord=document.getElementById("password");
var last_name=document.getElementById("lastName");
var first_name=document.getElementById("firstName");
var collegeName=document.getElementById("uni");
var majorName=document.getElementById("majoring");
event.preventDefault();
if(userName.value==""){
alert("User name needs to be specified");
userName.focus();
}
else{
if(!patternUsername.test(userName.value)){
alert("Invalid username");
userName.focus();
}
}
if(passWord.value==""){
alert("Password needs to be specified");
passWord.focus();
}
else{
if(passWord.length<8){
alert("Password needs to be longer than 8 characters");
passWord.focus();
}
}
if(first_name.value==""){
alert("First name needs to be specified");
first_name.focus();
}
else{
if(!pattern.test(first_name.value)){
alert("First name does not allow number");
first_name.focus();
}
}
if(last_name.value==""){
alert("Last name needs to be specified");
last_name.focus();
}
else{
if(!pattern.test(last_name.value)){
alert("Last name does not allow number");
last_name.focus();
}
}
if(collegeName.value==""){
alert("College name needs to be specified");
collegeName.focus();
}
else{
if(!pattern.test(collegeName.value)){
alert("Invalid college name");
collegeName.focus();
}
}
if(majorName.value==""){
alert("Major name needs to be specified");
majorName.focus();
}
else{
if(!pattern.test(majorName.value)){
alert("Invalid major name");
majorName.focus();
}
}
/*
if(first_name.value!=="" && last_name.value!==""&&email!==""&&pattern.test(first_name.value)&&pattern.test(last_name.value)){
alert("Perfect");
}
*/
}
check_form.addEventListener("submit",check);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<!--<link rel="stylesheet" href="./register.css">-->
<script src="./script.js" defer></script>
<style>
form div{
padding: 8px;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
</head>
<body>
<h1>Register</h1>
<form id="registration" action="register.php" method="post">
<div id='userName'>
<label for="username">Username: </label>
<input type="text" id="username" name="user_name"><br>
</div>
<div id="passWord">
<label for="password">Password: </label>
<input type="text" id="password" name="pass"><br>
</div>
<div id='firstname'>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="first_name"><br>
</div>
<div id="lastname">
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="last_name"><br>
</div>
<div id="uniName">
<label for="uni">College Name: </label>
<input type="text" id="uni" name="uni"><br>
</div>
<div id="majorName">
<label for="majoring">Major: </label>
<input type="text" id="majoring" name="major"><br>
</div>
<br>
<input type="submit" name="register" value="Register"><br><br>
Already have an account?
</form>
</body>
</html>
If you want to do your client-side validation. you must change the type of the button from (send) to (button). Then, create a function in JS to validate your form.
Call the function by clicking onclick button = "ItsFunctionForValidateAndSubmit ()".
After checking: Create a form submission method using javascript.
Here is a link to some sample form submissions.
Send POST data using XMLHttpRequest
<input type="buttom" name="register" value="Register" onclick="ItsFunctionForValidateAndSubmit()">
Related
I am building a multi-page form and it has a lot of conditional statements. Some of which deal with the display of particular DIVs based upon the selection of some other DIVs. To make my question simple I have created another form that works similarly, but is very short.
The first input field asks the "First Name." After it is filled with characters, two fields for "Middle Name," and "Last Name" appear. Originally, these two fields have "inline-style" of "display:none;" and hence are not displayed until the jQuery function displays them. Once the user fills out the form and hits submit, PHP validations run on the server.
For our purpose, let's fill the first input field then followed by two new fields displayed by jQUery, leave other fields blank and hit "submit." Of course, the PHP validations fail and we are shown the refreshed version of the form with all the form data gone and most importantly for my usage, the CSS display state for the two input fields gone. Now, I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I need help with restoring the form data on the first field followed by the display of the other two fields with their data. I sort of know how the localStorage works, but I could not make it work here.
I very much appreciate anyone giving this their time.
Once again, thank you very much.
Here goes the code:
<?php
$firstName = $middleName = $lastName = $email = $phone = $comment = $from = $name = $subject = $subject2 = $message2 = $headers = $headers2 = $result = $result2 = '';
$errors = array('firstName'=>'','middleName'=>'','lastName'=>'','email'=>'','phone'=>'','comment'=>' ');
if(isset($_POST['submit'])) { /**checks if the submit button is pressed or not. only executes below steps if the form is submitted.**/
//check first name input
if(empty($_POST['firstName'])){
$errors ['firstName'] = 'Please enter your First Name <br />';
} else {
$firstName = $_POST['firstName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $firstName)){
$errors ['firstName'] = 'Only letters are accepted <br />';
}
}
//check middle name input
if(empty($_POST['middleName'])){
$errors ['middleName'] = 'Please enter your Middle Name <br />';
} else {
$middleName = $_POST['middleName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $middleName)){
$errors ['middleName'] = 'Only letters are accepted <br />';
}
}
//check last name input
if(empty($_POST['lastName'])){
$errors ['lastName'] = 'Please enter your Last Name<br />';
} else {
$lastName = $_POST['lastName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $lastName)){
$errors ['lastName'] = 'Only letters are accepted <br />';
}
}
//check email input
if(empty($_POST['email'])){
$errors ['email'] = 'Please enter your E-mail Address <br />';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors ['email'] = 'Email must be a valid email address <br />';
}
}
//check phone number input
if(empty($_POST['phone'])){
$errors ['phone'] ='Please enter your Phone Number<br />';
} else {
$phone = $_POST['phone'];
if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}+$/', $phone)){
$errors ['phone'] = 'Only numbers separated by dashes are allowed <br />';
}
}
//check comment input
if(empty($_POST['comment'])){
$errors ['comment'] = 'Please provide your feedback <br />';
} else {
$comment = $_POST['comment'];
if(!preg_match('/^[\w,.!?\s]+$/',$comment)){
$errors ['comment'] = 'Only letters, commas, and periods are allowed <br />';
}
}
if(array_filter($errors)){
//let the user fill out form again
echo '<script type = "text/javascript">alert("Submission failed due to error in the input field. Please fill all the input fields and submit the form again. Thank you!") </script>';
} else {
header('location:thank-you');
}
//php to send message to both client and the owner
$mailto = "a#b.com"; //web owners email addresss
$from = $_POST['email']; //senders email address
$name = $_POST['firstName']; //user's name
$subject = "You received a message";
$subject2 = "Your message has been submitted successfully"; //message title for client email
$comment = "Client Name: ". $firstName. "wrote the following message". "\n\n". $_POST ['comment'];
$message = "Contact Form". "\n\n".
"From - ". $firstName. " ". $middleName. " ". $lastName. "\n\n".
"Email Id - ". $from. "\n\n". "Phone Number - ". $phone. "\n\n".
"FeedBack :". "\n\n". $_POST ['comment'];
$message2 = "Dear ". $firstName. ",". "\n\n". "Thank you for contacting us!";
$headers = "From: ". $from; //user entered email address
$headers2 = "From: ". $mailto; // this will receive to client
$result = mail($mailto, $subject, $message, $headers); //send email to the website owner
$result2 = mail($from, $subject2, $message2, $headers2); //send email to the user or form submitter
} // end of POST check
?>
<!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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1 /jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1 /jquery.validate.min.js"></script>
<link rel="stylesheet"href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label{display:block;}
.container{display:flex; flex-direction: row; flex-wrap: wrap;
margin-top:10rem; justify-content: left; margin-left:3rem;}
.flexItems{
margin-right:1rem; margin-bottom:2rem;
}
#submit{
margin-left:3rem;
width:20em;
}
.comment{
margin-left:3rem;
}
.red-text{
color:red;
}
</style>
<script>
$(document).ready(function() {
$("#fName").change(function(){
if($(this).val() != "" ){
$("#mName1").css("display","block");
$("#lName1").css("display","block");
} else {
$("#mName1").css("display","none");
$("#lName1").css("display","none");
}
})
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete = "off" id = "form">
<div class = "container">
<div class= "flexItems">
<label>First Name</label>
<input id = "fName" type = "text" name = "firstName" >
<div class = "red-text"><?php echo $errors['firstName']; ?></div>
</div>
<div class= "flexItems" id = "mName1" style = "display:none;">
<label>Middle Name</label>
<input id = "mName" type = "text" name = "middleName" >
<div class = "red-text"><?php echo $errors ['middleName']; ?></div>
</div>
<div class= "flexItems" id = "lName1"style = "display:none;" >
<label>Last Name</label>
<input id = "lName" type = "text" name = "lastName" >
<div class = "red-text"><?php echo $errors ['lastName']; ?></div>
</div>
<div class= "flexItems">
<label>Email Address</label>
<input id = "eAddress" type = "email" name = "email" >
<div class = "red-text"><?php echo $errors ['email']; ?></div>
</div>
<div class= "flexItems">
<label>Phone Number</label>
<input id = "pNumber" type = "tel" name = "phone" >
<div class = "red-text"><?php echo $errors ['phone']; ?></div>
</div>
<div class= "comment">
<label>Comment</label>
<textarea rows = "6" cols ="60" name = "comment" placeholder = "Please leave a comment. Thank you!" ></textarea>
<div class = "red-text"><?php echo $errors ['comment']; ?></div>
</div>
<div id = "submit">
<button type= "submit" id = "submit" value = "Send my message ASAP" name = "submit">Submit</button>
</div>
</div>
</form>
</body>
</html>
I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I would recommend using PHP to fill in the form values after submission and solve showing/hiding elements with JavaScript.
For example PHP would look like this: (using htmlspecialchars to escape quotes and other special characters and reading data directly from POST request)
<input
id="fName"
type="text"
name="firstName"
value="<?php echo htmlspecialchars($_POST['firstName']); ?>"
>
There is also possibility to keep values in localStorage if you prefer. I was able to find this jQuery plugin which does that - Persist.js.
Second task is to show/hide corresponding fields.
First of all, try to think about user experience when new fields appear or disappear. Maybe it's better to keep all the fields on the screen, disable/enable them etc. I can think of one case when fields can be hidden and it is when several options are presented for selection and the last option is 'other (please specify)' which allows to input custom response. I'll be adding this use case to the prototype bellow.
I'd recommend to create a single updateVisibility function that will show/hide needed blocks. It should be called when page loads (with data filled in with PHP) and when any form field is modified:
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") { // always use === or !== in JS for comparison
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
// hide inputs and clear values
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
});
P.S. I've noticed and fixed several errors in HTML:
tag attributes should not contain spaces - id="fName" (not id = "fName")
label tag requires for attribute - <label for="fName"> (where fName is an ID of some other element to which label will point)
Please find prototype code bellow (only HTML part, StackOverflow does not run PHP). Programming language field is an example of how I think user experience should be, I've kept Middle name/Last name fields functionality like in your question.
<!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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label {
display: block;
}
label.radio-label {
display: inline;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-top: 10rem;
justify-content: left;
margin-left: 3rem;
}
.flexItems {
margin-right: 1rem;
margin-bottom: 2rem;
}
#submit {
margin-left: 3rem;
width: 20em;
}
.comment {
margin-left: 3rem;
}
.red-text {
color: red;
}
</style>
<script>
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") {
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
// language other - show/hide language-other-block
if ($('input[name="language"][type="radio"]:checked').val() === 'other') {
$('#language-other-block').css('display', 'block');
} else {
$('#language-other-block').css('display', 'none');
$('#language-other-input').val('');
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete="off" id="form">
<div class="container">
<div class="flexItems">
<label for="fName">First Name</label>
<input id="fName" type="text" name="firstName">
<div class="red-text">
<?php echo $errors['firstName']; ?>
</div>
</div>
<div class="flexItems" id="mName1" style="display:none;">
<label for="mName">Middle Name</label>
<input id="mName" type="text" name="middleName">
<div class="red-text">
<?php echo $errors ['middleName']; ?>
</div>
</div>
<div class="flexItems" id="lName1" style="display:none;">
<label for="lName">Last Name</label>
<input id="lName" type="text" name="lastName">
<div class="red-text">
<?php echo $errors ['lastName']; ?>
</div>
</div>
<div class="flexItems">
<label for="eAddress">Email Address</label>
<input id="eAddress" type="email" name="email">
<div class="red-text">
<?php echo $errors ['email']; ?>
</div>
</div>
<div class="flexItems">
<label for="pNumber">Phone Number</label>
<input id="pNumber" type="tel" name="phone">
<div class="red-text">
<?php echo $errors ['phone']; ?>
</div>
</div>
<div class="flexItems">
<div>Programming language</div>
<div><input type="radio" name="language" value="js" id="language-js"><label class="radio-label"
for="language-js">JavaScript</label></div>
<div><input type="radio" name="language" value="php" id="language-php"><label class="radio-label"
for="language-php">PHP</label></div>
<div><input type="radio" name="language" value="other" id="language-other"><label class="radio-label"
for="language-other">other</label></div>
<div id="language-other-block" style="display: none;">
<label class="radio-label" for="">Please specify: </label>
<input type="text" name="language-other" id="language-other-input">
</div>
<div class="red-text">
<?php echo $errors ['language']; ?>
</div>
</div>
<div class="comment">
<label for="comment">Comment</label>
<textarea rows="6" cols="60" id="comment" name="comment"
placeholder="Please leave a comment. Thank you!"></textarea>
<div class="red-text">
<?php echo $errors ['comment']; ?>
</div>
</div>
<div id="submit">
<button type="submit" id="submit" value="Send my message ASAP" name="submit">Submit</button>
</div>
</div>
</form>
</body>
</html>
I have created a registration form, but the js file cannot call the php.
Are there anyone can give me some advise?
My question is when I click the submit button, there is no reaction. Do I have any mistakes? Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex, nofollow">
<title>Tittle</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="js/registration.js"></script>
<link href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css"
rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"
type="text/javascript"></script>
<script type="text/javascript" src="js/registration1.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function() {
$.extend( $.mobile , {
pageLoadErrorMessage: 'Either the page cannot be found or it cannot
be loaded.'
});
});
$(document).on("pageinit","#page", function() {
alert("pageinit is bound!");
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<div data-role="header">
<h1>Register</h1>
</div>
<form class="form" method="post" action="#">
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<button type="button" name="register" id="register"
class="btn">Submit</button>
</form>
</div>
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</body>
</html>
Below is the JS
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
Below is the PHP
$hostname = "127.0.0.1";
$username = "root";
$password = "123456";
$connection = mysql_connect($hostname, $username, $password) or die("Could
not open connection to database");
$db = mysql_select_db("mydb", $connection); // Selecting Database.
$name=$_POST['name1'];
$email=$_POST['email1'];
$password= sha1($_POST['password1']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}
else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values
('$name', '$email', '$password')"); // Insert query
if($query){
echo "Successfully Registered";
}
else
{
echo "Error";
}
}
else{
echo "This email is already registered. Please try again";
}
}
mysql_close ($connection);
?>
Your form action is empty try changing action="#" to action="register.php"
I have the below code which calls a .php file to insert data into a MySQL database, but cant seem to get the .php file to run. Any suggestions?
I am very new to script so i am trying this registration form example. The database, 'college', with its table, 'registration', seems to be fine, but no php code executes. It must be something really simple but i cant seem to work it out?
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
//alert(name); //This line reads fine
$.post("register.php",
{
name1: name,
email1: email,
password1: password
},
function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
<?php
$connection = mysql_connect("localhost", "root", "Winchester12"); // Establishing connection with server..
$db = mysql_select_db("college", $connection); // Selecting Database.
$name=$_POST['name1']; // Fetching Values from URL.
$email=$_POST['email1'];
echo $email;
$password= sha1($_POST['password1']); // Password Encryption, If you like you can also leave sha1.
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values ('$name', '$email', '$password')"); // Insert query
if($query){
echo "You have Successfully Registered.....";
}else
{
echo "Error....!!";
}
}else{
echo "This email is already registered, Please try another email...";
}
}
mysql_close ($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Squash Registration Form</title>
<meta name="robots" content="noindex, nofollow">
<!-- Include CSS File Here -->
<link rel="stylesheet" href="style.css"/>
<!-- Include JS File Here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="registration.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<form class="form" method="post" action="#">
<h2>Squash Registration Form</h2>
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<input type="button" name="register" id="register" value="Register">
</form>
</div>
</body>
</html>
It could be a path related issue.
you might want to review the path to the register.php file to be sure its in the right place.
It seems that nothing is passed to register.php file. Please try with 'ajax' instead of jquery post.
I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>
Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.
1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I'm building a form to be used to input data into a database. I have the basic form and validation built (I think). When I try testing it on my server/domain I keep getting the error undefined Index: Form Submit. I'm certain it's something minor, but I can't find my error. An extra set of eyes looking at this would be greatly appreciated.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<!--Designing my form-->
<h2>New Projects</h2>
<br>
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formProject']))
{
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if(empty($_POST['formClient']))
{
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if(empty($_POST['formLastName']))
{
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if(empty($_POST['formDateReceived']))
{
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>
You should change :
if($_POST['formSubmit'] == "Submit")
To :
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit")
When you're using form, you should ALWAYS verify at least once posted that your fields are set.
For example :
We have this quick form :
<form action="action_page.php" method="POST">
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
First note that on the I've put two attributes :
action : Which is where the form will be send
method : Which is how the form will be send
There are two inputs "firstname","lastname" and a button submit.
Let's say that on the "action_page.php" you want to display : "Hello, firstname lastname".
You could just do the following :
<?php
echo 'Hello, '.$_POST['firstname'].' '.$_POST['lastname'];
?>
And that will print out what you want.
But in the case where those fields would be empty that would create "Undefined Index"...
So to be sure that you won't be using variables that doesn't exist you should do the following :
<?php
//First we create an array that will errors if they occurs
$error = array();
//Then we test if firstname exist
if(isset($_POST['firstname'])) {
//if it does we can assign him.
$firstname = $_POST['firstname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your firstname';
}
//Then we test if lastname exist
if (isset($_POST['lastname'])) {
//if it does we can assign him.
$lastname = $_POST['lastname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your lastname';
}
//In the end we check if we have any error stocked:
if(empty($error)) {
//if it's empty we have all our required data to display our echo
echo 'Hello, '.$firstname.' '.$lastname;
}else{
//else let's show the error
print_r($error);
}
?>
This way we handle any possible "Undefined Index" before they occur and we are sure that our data will return something or at least have an error related.
For check if there was a POST action :-
if (!empty($_POST))
or
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Updated your code , check this
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<h2>New Projects</h2>
<?php
if ($_POST['formSubmit'] == "Submit") {
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if (empty($_POST['formProject'])) {
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if (empty($_POST['formClient'])) {
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if (empty($_POST['formLastName'])) {
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if (empty($_POST['formDateReceived'])) {
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if (!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>