I tried to create a sign up form where I need to validate if the the information entered is already exists in the database.
The code runs fine and can detect if the anything are already exists in the database.
The problem is it will clear all the form when it detects anything exists in database.
For example in below picture I try to input an email that already exists in database but in the second photo, all the form fields are clear out
Is there any ways to prevent the form from being cleared out? Its not convenience for user to re-fill the form again.
Below is my code.
<?php
include 'include/header.php';
include ('admin/include/dbcon.php');
?>
<script type="text/javascript">
$(document).ready(function() {
$("#inputState3").on('change', function() {
var val2 = $("#inputState3").val();
$.ajax({
url: "stdsec.php",
method: "post",
data: 'myvalue=' + val2
}).done(function(sec) {
$('#inputState1').html(sec);
})
})
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-sm-12 my-col">
<div class="outerdiv Signup-outerdiv">
<h1 class="Login-text">Sign Up</h1>
<div class="desc-text">New students on board are required to register to access the student
portal. <br> This only takes less than a minute. Already have an account? <a
href="studentlogin.php">Log
In</a> </div>
<hr>
<div class="InnerDiv InnerDiv2">
<form action="student_signup.php" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-12">
<input name="fname" title="Please enter your name as per IC." type="text"
class="form-control input-fields" placeholder="First Name" required
id="fullname">
<span class="text-danger" id="fname"></span>
</div>
<div class="form-group col-md-12">
<input name="fficnum" title="Enter IC Number without dashes ( - )." type="text"
class="form-control input-fields" placeholder="IC Number" required
id="std_ic">
<span class="text-danger" id="SICnum"></span>
</div>
<div class="form-group col-md-6">
<input name="pass" title="Please enter your password." type="password"
class="form-control input-fields" placeholder="Your Password" required
id="password">
<span class="text-danger" id="Spassword"></span>
</div>
<div class="form-group col-md-6">
<input name="Cpass" title="Please confirm your password." type="password"
class="form-control input-fields" placeholder="Confirm Password" required
id="cpassword">
<span class="text-danger" id="SCpassword"></span>
</div>
<div class="form-group col-md-6">
<input name="email" title="Please enter your email address." type="email"
class="form-control input-fields" placeholder="Email Address" required
id="email">
<span class="text-danger" id="Semail"></span>
</div>
<div class="form-group col-md-6">
<select name="gender" id="inputState2" class="form-control input-fields"
required="true">
<option value="">Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group col-md-6">
<select name="dep" id="inputState3" class="form-control input-fields"
required="true">
<option value="">Department</option>
<?php
$data = mysqli_query($sql_con,"Select *from departments");
while ($row = mysqli_fetch_array($data)){
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
</option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-6">
<select name="session" id="inputState1" class="form-control input-fields"
required="true">
<option value="">Session</option>
</select>
</div>
<div class="form-group col-md-6">
<input name="number" type="text" class="form-control input-fields"
placeholder="Contact Number" required id="number">
<span class="text-danger" id="Snumber"></span>
</div>
<div class="form-group col-md-6">
<div class="upload-div">
<input name="img" type="file" class="form-control" id="real-input"
hidden="hidden" required id="img">
<button type="button" id="custom-button">Upload Profile Picture
</button><br class="Br-Hide">
<span id="custom-text">No file chosen</span>
</div>
<span class="text-danger" id="imgerror"></span>
</div>
</div>
<div class="form-group">
<input name="address" type="text" class="form-control input-fields"
id="inputAddress" placeholder="Enter Your Address" required>
<span class="text-danger" id="Saddress"></span>
</div>
<center>
<input name="submit" type="submit" class="btn btn-primary btn-login-form2"
value="Create New Account" onclick="return validate2();">
</center>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
Password?</p>
-->
<!-- STUDENT FORM SECTION END -->
<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->
<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div><br>
<center><img src="../images/success-icon.svg" width="100" height="100"></center>
<div class="modal-body text-center">
<p class="password-errortxt">Congratulations, your account has been successfully created.</p>
<center>
<button name="submit" type="submit" class="btn btn-primary btn-login-form2"
onClick="parent.location='studentlogin.php'">Click Here to Login</button>
</center>
</div>
</div>
</div>
</div>
<?php
include('js/customUpload.js');
include('include/footer.php');
?>
<script type="text/javascript">
function validate2() {
var fname = document.getElementById('full_name').value;
var std_ic = document.getElementById('std_ic').value;
var email = document.getElementById('email').value;
var number = document.getElementById('number').value;
var address = document.getElementById('inputAddress').value;
var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
var emailCheck = /^([\w-\.]+#([\w-]*\.)+[\w-]{2,4})?$/;
var numberCheck = /^(\+?6?01)[0-46-9]-*[0-9]{7,8}$/;
if (fnameCheck.test(fname)) {
document.getElementById('fname').innerHTML = " ";
} else {
document.getElementById('fname').innerHTML = "Invalid Name!";
return false;
}
if (std_icCheck.test(std_ic)) {
document.getElementById('SICnum').innerHTML = " ";
} else {
document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
return false;
}
if (emailCheck.test(email)) {
document.getElementById('Semail').innerHTML = " ";
} else {
document.getElementById('Semail').innerHTML = "Invalid Email Address";
return false;
}
if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
document.getElementById('Snumber').innerHTML = " ";
} else {
document.getElementById('Snumber').innerHTML = "Invalid phone number.";
return false;
}
if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
document.getElementById('Saddress').innerHTML = "At least 20 characters";
return false;
} else {
document.getElementById('Saddress').innerHTML = " ";
}
}
</script>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$data = mysqli_query($sql_con,"select stdemail from students");
while ($row = mysqli_fetch_array($data)) {
$emaildb = $row['stdemail'];
if($emaildb == $email){
echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
exit();
}
}
$SICnum = $_POST['fficnum'];
$data = mysqli_query($sql_con,"select std_ic from students");
while ($row = mysqli_fetch_array($data)) {
$icnumdb = $row['std_ic'];
if($icnumdb == $SICnum){
echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
//exit();
return false;
}
}
$folder = "suploads/";
$filename = $_FILES['img']["name"];
$unique = uniqid().$filename;
$temname = $_FILES['img']["tmp_name"];
$size = $_FILES['img']["size"];
$target = $folder.basename($unique);
$filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
exit();
}
else if($size > 2097152){
echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
exit();
}
else {
move_uploaded_file($temname,$target);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$SICnum = $_POST['fficnum'];
$Cpass = $_POST['Cpass'];
$email = $_POST['email'];
$session = $_POST['session'];
$gender = $_POST['gender'];
$depart = $_POST['dep'];
$number = $_POST['number'];
$address = $_POST['address'];
mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");
echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/* echo "<script>alert('You are successfully registered')</script>"; */
}
}
?>
Use the following code
<?php
include 'include/header.php';
include ('admin/include/dbcon.php');
$email = "";
?>
<script type="text/javascript">
$(document).ready(function() {
$("#inputState3").on('change', function() {
var val2 = $("#inputState3").val();
$.ajax({
url: "stdsec.php",
method: "post",
data: 'myvalue=' + val2
}).done(function(sec) {
$('#inputState1').html(sec);
})
})
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-sm-12 my-col">
<div class="outerdiv Signup-outerdiv">
<h1 class="Login-text">Sign Up</h1>
<div class="desc-text">New students on board are required to register to access the student
portal. <br> This only takes less than a minute. Already have an account? <a
href="studentlogin.php">Log
In</a> </div>
<hr>
<div class="InnerDiv InnerDiv2">
<form action="student_signup.php" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-12">
<input name="fname" title="Please enter your name as per IC." type="text" value="<?php echo #$_POST['fname']; ?>"
class="form-control input-fields" placeholder="First Name" required
id="fullname">
<span class="text-danger" id="fname"></span>
</div>
<div class="form-group col-md-12">
<input name="fficnum" title="Enter IC Number without dashes ( - )." type="text" value="<?php echo #$_POST['fficnum']; ?>"
class="form-control input-fields" placeholder="IC Number" required
id="std_ic">
<span class="text-danger" id="SICnum"></span>
</div>
<div class="form-group col-md-6">
<input name="pass" title="Please enter your password." type="password" value="<?php echo #$_POST['pass']; ?>"
class="form-control input-fields" placeholder="Your Password" required
id="password">
<span class="text-danger" id="Spassword"></span>
</div>
<div class="form-group col-md-6">
<input name="Cpass" title="Please confirm your password." type="password" value="<?php echo #$_POST['Cpass']; ?>"
class="form-control input-fields" placeholder="Confirm Password" required
id="cpassword">
<span class="text-danger" id="SCpassword"></span>
</div>
<div class="form-group col-md-6">
<input name="email" title="Please enter your email address." type="email" value="<?php echo #$_POST['email']; ?>"
class="form-control input-fields" placeholder="Email Address" required
id="email">
<span class="text-danger" id="Semail"></span>
</div>
<div class="form-group col-md-6">
<select name="gender" id="inputState2" class="form-control input-fields"
required="true">
<option value="">Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group col-md-6">
<select name="dep" id="inputState3" class="form-control input-fields"
required="true">
<option value="">Department</option>
<?php
$data = mysqli_query($sql_con,"Select *from departments");
while ($row = mysqli_fetch_array($data)){
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
</option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-6">
<select name="session" id="inputState1" class="form-control input-fields"
required="true">
<option value="">Session</option>
</select>
</div>
<div class="form-group col-md-6">
<input name="number" type="text" value="<?php echo #$_POST['number']; ?>" class="form-control input-fields"
placeholder="Contact Number" required id="number">
<span class="text-danger" id="Snumber"></span>
</div>
<div class="form-group col-md-6">
<div class="upload-div">
<input name="img" type="file" class="form-control" id="real-input" value="<?php echo #$_POST['img']; ?>"
hidden="hidden" required id="img">
<button type="button" id="custom-button">Upload Profile Picture
</button><br class="Br-Hide">
<span id="custom-text">No file chosen</span>
</div>
<span class="text-danger" id="imgerror"></span>
</div>
</div>
<div class="form-group">
<input name="address" value="<?php echo #$_POST['address']; ?>" type="text" class="form-control input-fields"
id="inputAddress" placeholder="Enter Your Address" required>
<span class="text-danger" id="Saddress"></span>
</div>
<center>
<input name="submit" type="submit" class="btn btn-primary btn-login-form2"
value="Create New Account" onclick="return validate2();">
</center>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
Password?</p>
-->
<!-- STUDENT FORM SECTION END -->
<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->
<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div><br>
<center><img src="../images/success-icon.svg" width="100" height="100"></center>
<div class="modal-body text-center">
<p class="password-errortxt">Congratulations, your account has been successfully created.</p>
<center>
<button name="submit" type="submit" class="btn btn-primary btn-login-form2"
onClick="parent.location='studentlogin.php'">Click Here to Login</button>
</center>
</div>
</div>
</div>
</div>
<?php
include('js/customUpload.js');
include('include/footer.php');
?>
<script type="text/javascript">
function validate2() {
var fname = document.getElementById('full_name').value;
var std_ic = document.getElementById('std_ic').value;
var email = document.getElementById('email').value;
var number = document.getElementById('number').value;
var address = document.getElementById('inputAddress').value;
var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
var emailCheck = /^([\w-\.]+#([\w-]*\.)+[\w-]{2,4})?$/;
var numberCheck = /^(\+?6?01)[0-46-9]-*[0-9]{7,8}$/;
if (fnameCheck.test(fname)) {
document.getElementById('fname').innerHTML = " ";
} else {
document.getElementById('fname').innerHTML = "Invalid Name!";
return false;
}
if (std_icCheck.test(std_ic)) {
document.getElementById('SICnum').innerHTML = " ";
} else {
document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
return false;
}
if (emailCheck.test(email)) {
document.getElementById('Semail').innerHTML = " ";
} else {
document.getElementById('Semail').innerHTML = "Invalid Email Address";
return false;
}
if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
document.getElementById('Snumber').innerHTML = " ";
} else {
document.getElementById('Snumber').innerHTML = "Invalid phone number.";
return false;
}
if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
document.getElementById('Saddress').innerHTML = "At least 20 characters";
return false;
} else {
document.getElementById('Saddress').innerHTML = " ";
}
}
</script>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$data = mysqli_query($sql_con,"select stdemail from students");
while ($row = mysqli_fetch_array($data)) {
$emaildb = $row['stdemail'];
if($emaildb == $email){
echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
exit();
}
}
$SICnum = $_POST['fficnum'];
$data = mysqli_query($sql_con,"select std_ic from students");
while ($row = mysqli_fetch_array($data)) {
$icnumdb = $row['std_ic'];
if($icnumdb == $SICnum){
echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
//exit();
return false;
}
}
$folder = "suploads/";
$filename = $_FILES['img']["name"];
$unique = uniqid().$filename;
$temname = $_FILES['img']["tmp_name"];
$size = $_FILES['img']["size"];
$target = $folder.basename($unique);
$filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
exit();
}
else if($size > 2097152){
echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
exit();
}
else {
move_uploaded_file($temname,$target);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$SICnum = $_POST['fficnum'];
$Cpass = $_POST['Cpass'];
$email = $_POST['email'];
$session = $_POST['session'];
$gender = $_POST['gender'];
$depart = $_POST['dep'];
$number = $_POST['number'];
$address = $_POST['address'];
mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");
echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/* echo "<script>alert('You are successfully registered')</script>"; */
}
}
?>
Related
PHP Script & Validation:
function SampleInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['RegisterClient'])) {
$file = $_FILES['avatar']['name'];
$file_location = $_FILES['avatar']['tmp_name'];
$folder = "../Public/img/uploads/profile-picture/";
$new_file_name = strtolower($file);
$final_file = str_replace(' ', '-', $new_file_name);
$name = htmlspecialchars(trim($_POST['name'], ENT_QUOTES));
$username = htmlspecialchars(trim($_POST['username'], ENT_QUOTES));
$email = htmlspecialchars(trim($_POST['email'], ENT_QUOTES));
$password = htmlspecialchars(trim($_POST['password'], ENT_QUOTES));
$cpassword = htmlspecialchars(trim($_POST['cpassword'], ENT_QUOTES));
$role = htmlspecialchars(trim($_POST['role'], ENT_QUOTES));
if (move_uploaded_file($file_location, $folder.$final_file)) {
$image = $final_file;
}
if(empty($_POST['name']) || empty($_POST['username']) || empty($_POST['password']) || empty($_POST['cpassword']) || empty($_POST['role'])) {
$error = "All fields are required!";
} else {
$name = SampleInput($_POST['name']);
$username = SampleInput($_POST['username']);
$password = SampleInput($_POST['password']);
$cpassword =SampleInput($_POST['cpassword']);
$role = SampleInput($_POST['role']);
if (!preg_match('/^[a-zA-Z0-9\s]+$/',$name && $username && $password && $cpassword && $role)) {
$error = "Only letters and white space allowed";
}
}
$stmt = $db->prepare("INSERT INTO clients(name, username, email, password, avatar, role, registration_date) VALUES (:name, :username, :email, :password, :avatar, :role, NOW())");
$stmt->execute(array(
'name' => $name,
'username' => $username,
'email' => $email,
'password' => $password,
'avatar' => $image,
'role' => $role
));
$success = 'Registered!';
}
Modal:
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form action="" method="POST" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create user</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
if ($error) {
echo '<div class="mb-3">' . $error . '</div>';
} else if ($success) {
echo '<div class="mb-3">' . $success . '</div>';
}
?>
<div class="row gx-3 mb-3">
<div class="col-md-12">
<label class="small mb-1" for="login-fullname">Full name*</label>
<input class="form-control" name="name" type="text" placeholder="Valid full name" />
</div>
</div>
<div class="mb-3">
<label class="small mb-1" for="login-username">Username (how your name will appear to other users on the site)</label>
<input class="form-control" name="username" type="text" placeholder="Valid username" />
</div>
<div class="mb-3">
<label class="small mb-1" for="login-email">Email address</label>
<input class="form-control" name="email" type="text" placeholder="Valid email" />
</div>
<div class="row gx-3 mb-3">
<div class="col-md-6">
<label class="small mb-1" for="login-password">Password</label>
<input class="form-control" name="password" type="password" placeholder="Strong password" />
</div>
<div class="col-md-6">
<label class="small mb-1" for="login-cpassword">Confirm Password</label>
<input class="form-control" name="cpassword" type="password" placeholder="Strong password" />
</div>
</div>
<div class="row gx-3 mb-3">
<div class="card-body text-center">
<input type="file" required class="btn btn-primary" name="avatar">
<div class="small font-italic text-muted mb-6">JPG or PNG no larger than 5 MB</div>
</div>
</div>
<div class="mb-3">
<label class="small mb-1" for="selectRole">Select user role</label>
<select class="form-control" name="role">
<option value="">Select user role</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
<button type="submit" name="RegisterClient" class="btn btn-primary">Create</button>
</div>
</div>
</form>
</div>
</div>
I don't know where the problem is, I want the modal to remain open even if the problem or form has been submitted successfully. Now, with this code, if there is a problem with the submit form, the modal shuts down and if we open it again, the user can see error messages. Where am I wrong?
After a whole day, I resolve an issue with this.
$('#myModal').modal({
backdrop: 'static',
keyboard: false
})
With this code written above, a modal will be closed only if the user clicks on the close button. With this code, you disabled the close modal by pressing the ESC button on the keyboard.
I have a one page php webmail script.
PHP script code below:
<?php
function validEmail($email){
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
return false;
}
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false;
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
if (isset($_POST["submit"])) {
$ip=$_SERVER['REMOTE_ADDR'];
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$company = $_POST['company'];
$address = $_POST['address'];
$state = $_POST['state'];
$city = $_POST['city'];
$pincode = $_POST['pincode'];
$package = $_POST['package'];
$logo = $_POST['logo'];
$writeup = $_POST['writeup'];
$heared = $_POST['heared'];
$call = $_POST['call'];
$message = $_POST['message'];
$mailheader = "From: $email \r\n";
$formcontent .= "IP Address: $ip \n\n Full Name: $name \n E-mail: $email \n Mobile: $mobile \n Company: $company \n Address: $address \n state: $state \n City: $city \n Pin Code: $pincode \n Package: $package \n Logo: $logo \n Write-Ups: $writeup \n Heared: $heared \n Call Back: $call \n\n Message: $message";
$recipient = "***#***.com";
$subject = "Package Enquiry Form";
if (!$_POST['name']) {
$errName = 'Please enter your full name';
}
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['mobile']) {
$errMobile = 'Please enter your mobile number';
}
if (!$_POST['company']) {
$errCompany = 'Please enter your company name';
}
if (!$_POST['address']) {
$errAddress = 'Please enter your Address';
}
if (!$_POST['state']) {
$errState = 'Please enter your state';
}
if (!$_POST['city']) {
$errCity = 'Please enter your city';
}
if (!$_POST['pincode']) {
$errPinCode = 'Please enter your pin code';
}
if (!$_POST['package']) {
$errPackage = 'Please enter your package';
}
if (!$_POST['logo']) {
$errLogo = 'Do you want logo';
}
if (!$_POST['writeup']) {
$errWriteup = 'Do you need writeup';
}
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($recipient, $subject, $formcontent, $mailheader) or die("Error!")) {
$result='<div class="alert alert-success"><button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>Thank You! for placing your order with us. We will revert back to you shortly.</div>';
} else {
$result='<div class="alert alert-danger"><button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>Warning! There was a problem with your network connection. Please try again.</div>';
}
}
}
?>
and the html form code below:
<div class="form-group">
<div class="col-lg-12 col-sm-12">
<strong><?php echo $result; ?></strong>
</div>
</div>
<form id="registerform" method="post" name="registerform" action="">
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Full Name</label>
<input type="text" class="form-control" name="name" placeholder="Full Name *">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>E-Mail Address</label>
<input type="email" class="form-control" name="email" placeholder="Email *">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Contact Number</label>
<input type="number" class="form-control" name="mobile" placeholder="Mobile Number *">
<?php echo "<p class='text-danger'>$errMobile</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Company Name</label>
<input type="text" class="form-control" name="company" placeholder="Company Name *">
<?php echo "<p class='text-danger'>$errCompany</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Address</label>
<input type="text" class="form-control" name="address" placeholder="Address *">
<?php echo "<p class='text-danger'>$errAddress</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>City</label>
<input type="text" class="form-control cities" name="city" placeholder="City *">
<?php echo "<p class='text-danger'>$errCity</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>State</label>
<input type="text" class="form-control" name="state" placeholder="State *">
<?php echo "<p class='text-danger'>$errState</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Pin Code</label>
<input type="number" class="form-control" name="pincode" placeholder="Pin Code *">
<?php echo "<p class='text-danger'>$errPinCode</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Package</label>
<select class="form-control" name="package" size="1">
<option value="" selected="true" disabled="disabled">Choose Your Package *</option>
<option value="Basic Package">Basic Package</option>
</select>
<?php echo "<p class='text-danger'>$errPackage</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Logo</label>
<select class="form-control" name="logo" size="1">
<option value="" selected="true" disabled="disabled">Do you have Logo *</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
<option value="Required">Required</option>
</select>
<?php echo "<p class='text-danger'>$errLogo</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Write-up Text</label>
<select class="form-control" name="writeup" size="1">
<option value="" selected="true" disabled="disabled">Do you have Write-ups *</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
<option value="Required">Required</option>
</select>
<?php echo "<p class='text-danger'>$errWriteup</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>For our records</label>
<select class="form-control" name="heared" size="1">
<option value="" selected="true" disabled="disabled">Where you heared about us?</option>
<option value="Google Search">Google Search</option>
<option value="Others">Others</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 ">
<label>Write your Message</label>
<textarea id="message" class="form-control" name="message" rows="5" placeholder="Describe your details enquiry *"></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-6 ">
Request a phone call from a Company representative -
Yes: <input type="radio" value="Yes" name="call">
No: <input type="radio" value="No" name="call">
</div>
</div>
<div class="form-group">
<div class="col-lg-6 text-left">
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-default btn-lg button">
<input type="reset" class="btn btn-default btn-lg button" value="Clear">
</div>
</div>
</form>
</div>
</div>
This above code are in same page. Now i want to add captcha here and the captch code will be : captcha.php
<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165);
$fg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5, $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
and validate code will be: validate.php
<?php
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
}
else
{
die("Wrong Code Entered");
}
?>
and the HTML code of CAPTCHA will be:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
My question i integrate all this code in above page but the after validating page it goes to another page, and i want to it remains in same page after successful mail sent.
Good day, will anybody be willing to help me out here. I have this code:
<form id="form_advanced_validation" method="POST" action="">
<div class="row clearfix">
<div class="col-md-10">
<div class="form-group form-float">
<div class="form-line">
<input type="password" class="form-control" name="oldPass" required>
<label class="form-label">Old Password</label>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-10">
<div class="form-group form-float">
<div class="form-line">
<input type="password" class="form-control" name="newPass" required>
<label class="form-label">New Password</label>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-10">
<div class="form-group form-float">
<div class="form-line">
<input type="password" class="form-control" name="confPass" required>
<label class="form-label">Confirm Password</label>
</div>
</div>
</div>
</div>
<button class="btn btn-primary waves-effect" type="submit" name="sChanges">SUBMIT</button>
When submit button will be clicked, it will process the change password procedure, this is the code:
if (isset($_POST['sChanges'])) {
$dbC = new imsFunction();
$oldPasswrd = $dbC->txtInput($_POST['oldPass']);
$newPasswrd = $dbC->txtInput($_POST['newPass']);
$confPasswrd = $dbC->txtInput($_POST['confPass']);
$idNumber = $_SESSION['eID'];
if ($newPasswrd <> $confPasswrd) {
$_SESSION['passConfirm'] = FALSE;
echo '<script language="javascript">';
echo 'window.location = "change_Passwd.php";';
echo '</script>';
} else
$dbQry = $dbC->sRowQry('Select * From tbl_endUser Where id_number = ? and id_key = ?',[$idNumber, $oldPasswrd]);
if ($dbQry->rowCount() > 0) {
$changePass = $dbC->qryExec('Update tbl_endUser Set id_key=? Where id_number=?',[$newPasswrd, $idNumber]);
$_SESSION['passChange'] = TRUE;
echo '<script language="javascript">';
echo 'window.location = "change_Passwd.php";';
echo '</script>';
} else {
$_SESSION['wrongPass'] = FALSE;
echo '<script language="javascript">';
echo 'window.location = "change_Passwd.php";';
echo '</script>';
}
$dbC->disConnect(); }
What I want to do is when "$_SESSION['passChange']" has been set, I would like to call this javascript function:
function showSuccessMessage() {
swal("Good job!", "Password has been changed!", "success");}
I tried:
if (isset($_SESSION['passConfirm'])) { echo '<script type="javascript"> showSuccessMessage(); </script>'; }
but nothing happened.. Please guys, help me.
Don't forget to use session_start(); at beginning of each page.
Before calling the function, just use echo $_SESSION['passConfirm']; to ensure the session is set.
Now correct your code based on above 2 things and check
I have created a form based on the bootstrapious.com contact form tutorial. In my case I have changed it to populate a mysql database. Filling out the form and submitting it does get the information correctly in the database, but does not return a 'success' message or reset the form. I think the problem is in my javascript but am not sure. I would appreciate any help. Thanks
Here is my html
<!DOCTYPE html>
<html>
<head>
<title>Family Member</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<link href='custom.css' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h1>Family Member Form</h1>
<p class="lead">Please enter your information on the form below</p>
<form id="familyMember-form" method="post" action="familyMember.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_firstname">Firstname *</label>
<input id="form_firstname" type="text" name="firstName" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="lastName" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cellPhone">Cell Phone</label>
<input id="form_cellPhone" type="tel" name="cellPhone" class="form-control" placeholder="Please enter your cell phone number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_password">Password*</label>
<input id="form_password" type="password" name="password" class="form-control" placeholder="Please enter your password*">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_passwordConfirmation">Confirm Password*</label>
<input id="form_passwordConfirmation" type="password" name="passwordConfirmation" class="form-control" placeholder="Please confirm your password*">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_familyCode">Family Code *</label>
<input id="form_familyCode" name="familyCode" class="form-control" placeholder="Please Enter Family Code *" rows="4" required="required" data-error="Please,leave us a message.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p></p>
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="validator.js"></script>
<script src="familyMember.js"></script>
</body>
</html>
Here is my php
$okMessage = 'Family member has successfully added.';
$errorMessage = 'there was an error';
try
{
$pdo = new PDO('mysql:host=localhost; dbname=mydb', "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server:' . $e->getMessage();
include 'output.html.php';
exit();
}
//$output = 'Database connection established.';
//include 'output.html.php';
$firstName = $_POST['firstName'];
//echo $firstName;
//echo '<br>';
$lastName = $_POST['lastName'];
//echo $lastName;
//echo '<br>';
$email = $_POST['email'];
//echo $email;
//echo '<br>';
$cellPhone = $_POST['cellPhone'];
//echo $cellPhone;
//echo '<br>';
$password = $_POST['password'];
//echo $password;
//echo '<br>';
$familyCode = $_POST['familyCode'];
//echo $familyCode;
//echo '<br>';
try{
$sql = 'INSERT INTO familyMembers(FirstName, LastName, Email, Password, cell_phone, familyCode)
Values(:FirstName, :LastName, :Email, :Password, :cell_phone, :familyCode)';
$statement = $pdo -> prepare($sql);
$statement -> execute(array(':FirstName' => $firstName, ':LastName' =>$lastName, ':Email'=> $email, ':Password'=> $password, ':cell_phone' => $cellPhone, ':familyCode' => $familyCode));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
Here is my javascript
$(function () {
$('#familyMember-form').validator();
$('#familyMember-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "familyMember.php";
alert(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
alert(url);
alert(data);
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
alert(messageAlert);
alert(messageText);
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#familyMember-form').find('.messages').html(alertBox);
$('#familyMember-form')[0].reset();
}
}
});
return false;
}
});
});
I have problem with ajax modal on my codeigniter project. I don't know why the submit button didn't work. the modal can be shown, but when I click the save button, nothing happens.
this is my javascript :
<script type="text/javascript" src="<?php echo site_url('assets/js/jquery.js'); ?>"></script>
<script src="<?php echo site_url('assets/js/bootstrap.min.js');?>"> </script>
<script type="text/javascript">
$('#submit').click(function() {
var form_data = {
name: $('#nama').val(),
email: $('#email').val(),
};
$.ajax({
url: "<?php echo site_url('adminproses/update'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
$('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
$('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
return false;
});
});
this my modal form :
<div class="modal fade" id="edit-modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Detail Data Anda</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_user"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Nomor Induk Pegawai</label>
<div class="col-md-9">
<input name="NIP" placeholder="Nomor Induk Pegawai" id="NIP" class="form-control" type="text" value="<?php echo $tampil['NIP'];?> ">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nama</label>
<div class="col-md-9">
<input name="nama" placeholder="Nama Lengkap Anda" id="nama" class="form-control" type="text" value="<?php echo $tampil['nama'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Alamat</label>
<div class="col-md-9">
<textarea name="alamat" id="alamat" placeholder="Jalan A Nomor 1, Kelurahan A, Desa A, Kecamatan A, Kabupaten A, Provinsi A." class="form-control" ><?php echo $tampil['alamat'];?></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nomor HP</label>
<div class="col-md-9">
<input name="no_hp" placeholder="081111111111" id="no_hp" class="form-control" type="text" value="<?php echo $tampil['no_hp'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">E-mail</label>
<div class="col-md-9">
<input name="email" placeholder="email#service.com" id="email" class="form-control" type="text" value="<?php echo $tampil['email'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Kategori</label>
<div class="col-md-9">
<select name="id_katuser" class="form-control" id="kategori">
<option value="">Pilih Kategori</option>
<?php foreach ($katuser as $kat){?>
<option value="<?php echo $kat['id_katuser']; ?>" <?php if($kat['id_katuser']==$tampil['id_katuser']){echo "selected";}?>>
<?php echo $kat['nama_katuser']; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Username</label>
<div class="col-md-9">
<input name="username" placeholder="Username" id="username" class="form-control" type="text" value="<?php echo $tampil['username'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password</label>
<div class="col-md-9">
<input name="password" placeholder="Password" id="password" class="form-control" type="text" value="<?php echo $tampil['password'];?>">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div id="alert-msg"></div>
<div class="modal-footer">
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
and the controller :
public function update(){
//set validation rules
$this->form_validation->set_rules('NIP', 'nip', 'trim|required|xss_clean');
$this->form_validation->set_rules('nama', 'email', 'trim|required|xss_clean');
$this->form_validation->set_rules('alamat', 'alamat', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
$this->form_validation->set_rules('no_hp', 'no_hp', 'trim|required|xss_clean');
$this->form_validation->set_rules('kategori', 'kategori', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
//run validation check
if ($this->form_validation->run() == FALSE){
//validation fails
echo validation_errors();
}
else{
//get the form data
$NIP = $this->input->post('NIP');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$no_hp = $this->input->post('no_hp');
$email = $this->input->post('email');
$id_katuser = $this->input->post('kategori');
$username = $this->input->post('username');
$password = $this->input->post('password');
}
}
Thank you for the help.
Use this to post the data
$('#btnSave').click(function(e) {
e.preventDefault();
var form_data = {
name: $('#nama').val(),
email: $('#email').val()
};
$.ajax({
url: '<?php echo site_url('adminproses/update'); ?>',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
$('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
$('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
return false;
});
});