calling javascript function from php form submit - javascript

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

Related

Input validation - stop form from being clear out

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>"; */
}
}
?>

Trouble getting input form to return 'success' message and to reset

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;
}
});
});

Cannot get response from AJAX in Javascript

I made a simple AJAX application, it worked fine for sometime, but I don't know what I did wrong with the app which does not run properly. I am putting all info here:
This is HTML Code:
<div class="col-lg-6 col-md-6 contact-wthree2">
<h3 class="head2">Your Comments</h3>
<form onsubmit="submit_form();">
<div class="row">
<div class="form-group col-lg-6 col-md-6 col-sm-6 slideanim">
<input type="text" class="form-control first-name" id="firstname" placeholder="First Name"
required/>
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6 slideanim">
<input type="text" class="form-control last-name" id="lastname" placeholder="Last Name"
required/>
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6 slideanim">
<input type="email" class="form-control mail" id="mail" placeholder="Your Email" required/>
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6 slideanim">
<input type="tel" class="form-control pno" id="phone" placeholder="Your Phone Number"
required/>
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12 slideanim">
<textarea class="form-control" rows="6" id="message" placeholder="Your Message" required></textarea>
</div>
<div class="form-group col-lg-12 slideanim">
<button type="submit" class="btn btn-lg btn-outline">Send Message</button>
</div>
</div>
</form>
</div>
</div>
<button class="btn btn-primary" id="clickme" data-toggle="modal" data- target="#dialog" style="display:none">Open Dialog</button>
<div class="modal fade" id="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" id="response">
</div>
</div>
</div>
</div>
Then I wrote Javascript Code as follows:
<script>
var xmlhttp = new XMLHttpRequest();
var firstname = document.getElementById('firstname').value,
lastname = document.getElementById('lastname').value,
email = document.getElementById('mail').value,
contact = document.getElementById('phone').value,
message = document.getElementById('message').value;
function submit_form()
{
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
document.getElementById('response').innerHTML = xmlhttp.responseText;
document.getElementById('clickme').click();
firstnameinp.value="";
lastnameinp.value="";
emailinp.value="";
contactinp.value="";
messageinp.value="";
}
}
xmlhttp.open('POST','process_comments.php?firstname=' + firstname+'&lastname='+lastname
+'&email='+email+'&contact='+contact+'&message='+message+'',true);
xmlhttp.send();
}
</script>
And here is my PHP file (process_comments.php):
<?php
include('connection.php');
$firstname = "";
$lastname = "";
$email = "";
$contact = "";
$message = "";
$sql = "";
$table = "comments";
if (isset($_REQUEST['firstname']) && isset($_REQUEST['lastname']) && isset($_REQUEST['email']) && isset($_REQUEST['contact']) && isset($_REQUEST['message'])) {
//echo "Hi";
$firstname = "'" . $_REQUEST['firstname'] . "'";
$lastname = "'" . $_REQUEST['lastname'] . "'";
$email = "'" . $_REQUEST['email'] . "'";
$contact = $_REQUEST['contact'];
$message = "'" . $_REQUEST['message'] . "'";
$sql = "INSERT INTO {$table} VALUES (NULL,{$firstname},{$lastname},{$email},{$contact},{$message})";
if (mysqli_query($conn, $sql)) {
echo "<div class='alert alert-success' ><h4>Your message has successfully been sent.</h4></div>
<div class=\"text-right\">
<button class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button>
</div>";
} else {
echo "<div class='alert alert-danger' ><h4> Message sending failed.</h4></div>
<div class=\"text-right\">
<button class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button>
</div>";
}
} else {
echo "<div class='alert alert-danger' ><h4>Message sending failed.</h4></div>
<div class=\"text-right\">
<button class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button>
</div>";
}
This worked for some time, but now when I run this, it does not give the xmlhttp.responseText.
Anybody please help.

show validation in ajax in codeigniter

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;
});
});

keeping bootstrap modal active

hi how to keep bootstrap modal active after clicking submit button. In my case after clicking submit button it refresh the page so it close the modal. In my modal form i have a textboxes that when you click submit it will save the data in database. Now i have a php code that check the textboxes if their empty it will show/say the error and if not empty it will says success.
Thanks in advance who will help.
This is my code
<div class="modal fade" id="addtopic" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<form method="POST" action="index.php" role="form" id="saveform">
<div class="modal-body">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</div>
<div class="modal-footer">
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo "<p class='pull-left'> Topic Save! </p>";
}else {
echo "<p class='pull-left'>Failed to Save</p>";
die($db->error);
}
}else {
echo "<p class='pull-left'>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
?>
<button type="submit" name="Sbt" class="btn btn-primary" >Save changes</button>
<button data-dismiss="modal" class="btn btn-danger">Close</button>
</div>
</form>
</div>
</div>
</div>
Where you return
echo "<p class='pull-left'>All Fields are required</p>";
Add this bit of code to open the modal on page load.
<script type="text/javascript">
$(window).load(function(){
$('#addtopic').modal('show');
});
</script>

Categories