Form validation with AJAX return - javascript

I have a contact form that, when submit is clicked, I want to be validated.
If all fields return valid, then I want AJAX to return a Processing message, then, when successful, a message appears with the imputed name.
My Form content is:
<form onsubmit="return validateForm">
<input id="fname" class="textbox" name="fname" placeholder="First Nname" type="text" required="required" /><p>
<input id="sname" class="textbox" name="sname" placeholder="Surname" type="text" required="required" /><p>
<input id="email" class="textbox" name="email" placeholder="Email Address" type="email" required="required" /><p>
<input id="number" class="textbox" name="number" placeholder="Contact Number" type="email" /><p>
<textarea rows="10" id="message" class="textarea" name="message" placeholder="Message" required="required" ></textarea><p>
<input fname="myBtn" class="button" type="submit" value="Submit" onClick="javascript:ajax_post();">
My Form Validation content is:
function validateForm()
{
var fname=document.forms["Form"]["fname"].value;
var sname=document.forms["Form"]["sname"].value;
var x=document.forms["Form"]["email"].value;
var telnum=document.forms["Form"]["telnum"].value;
var message=document.forms["Form"]["message"].value;
if(fname==null||fname=="")
{
alert("please enter your first name");
return false;
}
if(sname==null||sname=="")
{
alert("please enter your surname");
return false;
}
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if(atpos<1||dotpos<atpos+2||dotpos+2>x.lenght)
{
alert("Not a valid email address.");
return false;
}
if(message==null||message=="")
{
alert("please enter a message");
return false;
}
}
The AJAX Script is:
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "/additional/formfeedback.php";
var fname = document.getElementById("fname").value;
var vars = "fname="+fname;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "Processing...";
}
And the returned PHP is:
<?php
echo 'Thank you '. $_POST['fname'] . ', we have recieved your message and will be back in touch shortly';
?>
When the Submit button is clicked, the PHP content is returned, then the validation starts - obviously too late.
How do I get this to validate correctly, then carry out the AJAX script? I don't want to use any additional libraries, such a jQuery. Thanks in advance.

you should set the validation to the submit button, and then at the bottom of the validation script, call the ajax script.

Call ajax_post at the end of your validateForm method.

One point ... you don't need "javascript:" in an onclick. It's already expecting javascript.
Also, if you want to submit data with Ajax, change the button to type="button" (not submit)

<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var password = $("#Password").val();
var cpassword = $("#cpassword").val();
var gender = $("input[name=gender]:checked").val();
var dob = $("#dob").val();
var image = $("#image").val();
var status = $("#status").val();
var submit = $("#submit").val();
var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+
'&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+
'&submit'+submit;
if(fname=="" || lname=="" || email==""){
alert("please fill the fields");
}else if(fname.length < 5 || fname.length > 20){
alert("user name must be between 5 to 20 characters");
}else if(password.length < 5 || password.length > 8){
alert("password must be between 5 to 8 characters");
}else if(!gender){
alert("please select your gender");
}else if(!dob){
alert("please select your birth day");
}else{
$.ajax({
type:"POST",
url:"create-user.php",
data:dataString,
cache:false,
success:function(result){
alert(result);
}
});//ajax closed
}
return false;
});
});
</script>
<div id="content" class="col-lg-10 col-sm-10">
<!-- content starts -->
<div>
<ul class="breadcrumb">
<li>
Home
</li>
<li>
Forms
</li>
</ul>
</div>
<div class="box-content">
<div id="userRegis">
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input class="form-control" id="fname" placeholder="Enter First Name" type="text" name="fname">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last Name</label>
<input class="form-control" id="lname" placeholder="Enter Last Name" type="text">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input class="form-control" id="email" placeholder="Enter Email" type="text">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input class="form-control" id="Password" placeholder="Enter Password" type="password">
</div>
<div class="form-group">
<label for="exampleInputEmail1">confirm Password</label>
<input class="form-control" id="cPassword" placeholder="Enter confirm Password" type="password" name="cpassword">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Gender</label>
<div class="radio">
<label>
<input type="radio" name="gender" id="gender" value="MALE">Male
</label>
<label>
<input type="radio" name="gender" id="gender" value="FEMALE">Female
</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">date of birth</label>
<input class="form-control" id="dob" placeholder="Enter Password" type="date" name="dob">
</div>
<div class="form-group">
<label for="exampleInputEmail1">image</label>
<input class="form-control" id="image" placeholder="Enter Password" type="file" name="image">
</div>
<div class="form-group">
<div class="control-group">
<label class="control-label" for="selectError">Status</label>
<div class="controls">
<select id="status" data-rel="chosen" name="status">
<option value="0">SELECT</option>
<option value="1">ACTIVE</option>
<option value="2">PENDING</option>
</select>
</div>
</div>
<br>
<input type="submit" name="submit" id="submit" value="create user" class="btn btn-default">
</div>
</div>
</div>
</div>

Related

Form Validation using Javascript Regular Expression?

I'm creating a registration form which contains userid, name, email, password, confirm password and affiliation. These fields are validated using regular expression in javascript. I want the error to be displayed in the form and I'm using span tag to achieve this. I don't know where I'm going wrong since its not being validated.
function validation() {
var userid = document.getElementById('userid').value;
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var psw = document.getElementById('psw').value;
var psw_repeat = document.getElementById('psw_repeat').value;
var usercheck = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/;
var fnamecheck = /^[A-Za-z. ]{3,20}$/;
var lnamecheck = /^[A-Za-z. ]{3,20}$/;
var emailcheck = /^[A-Za-z_]{3,}#[A-Za-z]{3,}[.]{1}[A-Za-z.]{2,6}$/;
var pswcheck = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9##$%^&*]{8,15}$/;
if (usercheck.test(userid)) {
document.getElementById('usererror').innerHTML = "";
} else {
document.getElementById('usererror').innerHTML = "**User id is invalid";
return false;
}
if (fnamecheck.test(fname)) {
document.getElementById('fnameerror').innerHTML = "";
} else {
document.getElementById('fnameerror').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (emailcheck.test(email)) {
document.getElementById('mail').innerHTML = "";
} else {
document.getElementById('mail').innerHTML = "**Email-id is invalid";
return false;
}
if (pswcheck.test(psw)) {
document.getElementById('pass').innerHTML = "";
} else {
document.getElementById('pass').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (psw.match(psw_repeat)) {
document.getElementById('conpass').innerHTML = "";
} else {
document.getElementById('conpass').innerHTML = "**Password doesnot match";
return false;
}
}
<html>
<body>
<form id="reg" method="post" onsubmit="return validation()">
<legend><b>Create an account</b></legend>
<div class="form-group">
<label for="userid">User id</label>
<input type="text" placeholder="Enter your User id" class="form- control" name="userid" id="userid">
<span id="usererror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="fname">First Name</label>
<input type="text" placeholder="Enter your First name" class="form- control" name="fname" id="fname">
<span id="fnameerror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="email">Email id</label>
<input type="email" placeholder="Enter your Email-id" class="form- control" name="email" >
<span id="mail" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw">Password</label>
<input type="password" placeholder="Enter Password" class="form- control" id="psw">
<span id="pass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw_repeat">Confirm Password</label>
<input type="password" placeholder="Re-enter Password" class="form-control" id="psw_repeat" >
<span id="conpass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<div class="dropdown">
<label for="affiliation">Affiliation</label>
<select class="form-control">
<option value="alumni" name="affiliation">Alumni</option>
<option value="faculty" name="affiliation">Faculty</option> <option value="student" name="affiliation">Student</option>
</select>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="submit" name="submit">Register</button>
<button type="reset" class="btn btn-danger">Cancel</button>
</div>
</form>
</body>
</html>
#lname does not exist, so document.getElementById('lname') is null; trying to look up .value on that is breaking your function.
lname this filed is missing in js file and also some filed not have id value in html file.
<html>
<body>
<form id="reg" method="post" onsubmit="return validation()">
<legend><b>Create an account</b></legend>
<div class="form-group">
<label for="userid">User id</label>
<input type="text" placeholder="Enter your User id" class="form-control" name="userid" id="userid">
<span id="usererror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="fname">First Name</label>
<input type="text" placeholder="Enter your First name" class="form-control" name="fname" id="fname">
<span id="fnameerror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="email">Email id</label>
<input type="email" placeholder="Enter your Email-id" class="form-control" name="email" id="email">
<span id="mail" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw">Password</label>
<input type="password" placeholder="Enter Password" class="form-control" id="psw">
<span id="pass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw_repeat">Confirm Password</label>
<input type="password" placeholder="Re-enter Password" class="form-control" id="psw_repeat">
<span id="conpass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<div class="dropdown">
<label for="affiliation">Affiliation</label>
<select class="form-control">
<option value="alumni" name="affiliation">Alumni</option>
<option value="faculty" name="affiliation">Faculty</option>
<option value="student" name="affiliation">Student</option>
</select>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="submit" name="submit">Register</button>
<button type="reset" class="btn btn-danger">Cancel</button>
</div>
</form>
</body>
</html>
//Script file
function validation() {
var userid = document.getElementById('userid').value;
var fname = document.getElementById('fname').value;
// var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var psw = document.getElementById('psw').value;
var psw_repeat = document.getElementById('psw_repeat').value;
var usercheck = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/;
var fnamecheck = /^[A-Za-z. ]{3,20}$/;
//var lnamecheck = /^[A-Za-z. ]{3,20}$/;
var emailcheck = /^[A-Za-z_]{3,}#[A-Za-z]{3,}[.]{1}[A-Za-z.]{2,6}$/;
var pswcheck = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9##$%^&*]{8,15}$/;
if (usercheck.test(userid)) {
document.getElementById('usererror').innerHTML = "";
} else {
document.getElementById('usererror').innerHTML = "**User id isinvalid";
return false;
}
if (fnamecheck.test(fname)) {
document.getElementById('fnameerror').innerHTML = "";
} else {
document.getElementById('fnameerror').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (emailcheck.test(email)) {
document.getElementById('mail').innerHTML = "";
} else {
document.getElementById('mail').innerHTML = "**Email-id is invalid";
return false;
}
if (pswcheck.test(psw)) {
document.getElementById('pass').innerHTML = "";
} else {
document.getElementById('pass').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (psw.match(psw_repeat)) {
document.getElementById('conpass').innerHTML = "";
} else {
document.getElementById('conpass').innerHTML = "**Password doesnot match";
return false;
}
}

HTML form showing error even after entering correct values

I have a contact form including validations. HTML form shows an error on entering wrong values but after correcting the values and entering appropriate data it continues to show the same error. I am validating the form using pattern attribute in the form.
The code below includes the form and the script which is used for validation.
Here is the part of the document:
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Create Account</h1>
<div>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" pattern='^[a-zA-Z ]*$' autofocus required/>
</div>
<!--<?php if(isset($msg_name)) echo "<script>alert('$msg_name')</script>";?>-->
<div>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus required />
</div>
<!--<?php if(isset($msg_username)) echo "<script>alert('$msg_username')</script>";?>-->
<div>
<input type="email" name="email" id="email" class="form-control" placeholder="Email" pattern='^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$' autofocus required/>
</div>
<!--<?php if(isset($msg_email)) echo "<script>alert('$msg_email')</script>";?>-->
<div>
<input type="text" name="phone" id="phone" class="form-control" placeholder="PhoneNumber" autofocus required />
</div>
<div>
<input type="password" name="password" id="password1" class="form-control" placeholder="Password" autofocus required />
<input type="checkbox" onclick="signup_pass()">Show Password
</div><br>
<!--<?php if(isset($msg_password)) echo "<script>alert('$msg_password')</script>";?>-->
<div>
<input class="btn btn-default submit" type="submit" name="submit" value="SIGNUP" >
<?php if(isset($error)) echo "<script>alert('$error')</script>";?>
<?php if(isset($message)) echo "<script>alert('$message')</script>";?>
</div>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">Already a member ?
Log in
</p>
<div class="clearfix"></div>
<br />
<div>
<h1> Elegocart!</h1>
<p>©2018 All Rights Reserved.Privacy and Terms</p>
</div>
</div>
</form>
</section>
</div>
</div>
</div>
<script>
function login_pass() {
var x = document.getElementById("password");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function signup_pass() {
var x = document.getElementById("password1");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
var name = document.getElementById('name');
var username = document.getElementById('username');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var password = document.getElementById('password1');
name.oninvalid = function(event)
{
event.target.setCustomValidity("Name should include only alphabets and white space");
}
username.oninvalid = function(event)
{
event.target.setCustomValidity("a-z, 0-9, underscore, hyphen");
}
email.oninvalid = function(event)
{
event.target.setCustomValidity("Must be of valid email format");
}
phone.oninvalid = function(event)
{
event.target.setCustomValidity("Enter aaa valid phone number");
}
password.oninvalid = function(event)
{
event.target.setCustomValidity("Password : must contain uppercase,lowercase,numbers and special characters , and shouldbe minimum of 8 characters long");
}
</script>
Probably your function is wrong try something like this :
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Unable to validate more than the first entry in a form

I am trying to validate a form using Javascript but as of right now, it is validating the first form entry and ignoring the rest. If I have less than 6 characters, it'll stop the form from submitting. Once I add more characters, it'll act like the form is fine and submit it, even if everything else is wrong.
HTML:
<form class="form-horizontal" onsubmit="return validator(this);">
<div class="form-group">
<label class="control-label col-xs-3" for="userName">Username:</label>
<div class="col-xs-9">
<!-- USERNAME --><input type="text" class="form-control" id="userName" placeholder="Username"maxlength="50">
<p id="userNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password">Password:</label>
<div class="col-xs-9">
<!-- PASS1 --><input type="password" class="form-control" id="Password" placeholder="Password"maxlength="50">
<p id="password1Emsm"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password2">Re-enter Password:</label>
<div class="col-xs-9">
<!-- PASS2 --><input type="password" class="form-control" id="Password2" placeholder="Re-enter Password"maxlength="50">
<p id="password2Emsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="firstName">First Name:</label>
<div class="col-xs-9">
<!-- FIRSTNAME --><input type="text" class="form-control" id="firstName" placeholder="First Name"maxlength="50">
<p id="firstNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="lastName">Last Name:</label>
<div class="col-xs-9">
<!-- LASTNAME --><input type="text" class="form-control" id="lastName" placeholder="Last Name"maxlength="50">
<p id="lastNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="zipCode">Zip Code:</label>
<div class="col-xs-9">
<!-- ZIPCODE --><input type="text" class="form-control" id="zipCode" placeholder="Zip Code" maxlength="10">
<p id="zipCodeEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="phoneNumber">Phone Number:</label>
<div class="col-xs-9">
<input type="tel" class="form-control" id="phoneNumber" placeholder="Phone Number"maxlength="12">
<p id="phoneNumberEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="inputEmail">Email Address:</label>
<div class="col-xs-9">
<!-- EMAILADDRESS --><input type="email" class="form-control" id="inputEmail" placeholder="email#address.com"maxlength="100">
<p id="emailEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group"><!-- BUTTONS -->
<div class="col-xs-offset-3 col-xs-9">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</form>
JS:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var password2 = document.getElementById("Password2");
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var email = document.getElementById("inputEmail");
var passwordFormat = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var emailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
return false;
}
else if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
return false;
}
else if (!password.value.match(passwordFormat)) {
document.getElementById("password1Emsg").innerHTML = "Enter correct password format.";
return false;
}
else if (password.value != password2.value) {
document.getElementById("password2Emsg").innerHTML = "Passwords do not match.";
return false;
}
else if (email.value.length < 1) {
document.getElementById("emailEmsg").innerHTML = "Please enter an email.";
return false;
}
else if (!email.value.match(emailFormat)) {
document.getElementById("emailEmsg").innerHTML = "Enter correct email format.";
return false;
}
else {
return true;
}
}
I have removed all the elses and have removed the return statement at the bottom and it made no difference to how it funtioned.
Remove all the else if clasues, replace them by pure if and remove the return statement.
Now your code at least, will run through and display all error messages, instead of only the first one.
Now you will need a flag, that signifies, that your form is invalid and disables the Submit button:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var isFormValid = true;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
isForValid = false;
}
if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
isForValid = false;
}
/**check if form is Vald **/
if(!isFormValid){
//disable submit button
}
}
But if you can avoid it: use as much, of the built-in function of html as possible. There is no reason you could not just use
<input type="email" id="emailField" required />
and then call document.getElementById('emailField').checkValidity();

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

Form Validation with jQuery - Weird Redirect

Alright, so I'm trying to do form validation with jQuery. Not sure why but when you click submit it redirects you to the page you're at already.
The forms action is blank and I included the javascript file in the header.
I will put the code below. Let me know if you see whats wrong. I want it to validate with jQuery then send you to a php file with those values in the method POST.
Register.js:
$(document).ready(function() {
$('button[name=regsubmit]').click(function(){
var fname = $('input[name=regfirstname');
var lname = $('input[name=reglastnaame');
var email = $('input[name=regemail');
var password = $('input[name=regpassword');
var repeatpassword = $('input[name=regrepeatpassword');
var username = $('input[name=regusername');
var atpos = email.indexOf("#");
var dotpos = email.indexOf(".");
if (fname==null || fname=="")
{
alert('First name must be filled out!');
return false;
}
if (lname==null || lname=="")
{
alert('Last name must be filled out!');
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert('Not a valid e-mail address!');
return false;
}
if (username==null || username=="")
{
alert("Username field must be filled out!");
return false;
}
if (password==null || password=="")
{
alert("Subject field must be filled out!");
return false;
}
if (repeatpassword==null || repeatpassword=="")
{
alert("Repeat password field must be filled out!");
return false;
}
if (password != repeatpassword)
{
alert("The passwords do not match!");
return false;
}
else
{
location.href="register.php";
}
});
});
Form:
<form name="register" method="POST">
<fieldset>
<div class="form-container row-fluid">
<div class="span6">
<div class="control-group">
<label class="control-label" for="regfirstname">First Name</label>
<div class="controls">
<input id="regfirstname" tabindex="1" name="regfirstname" type="text" placeholder="First Name" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regusername">Username</label>
<div class="controls">
<input id="regusername" tabindex="3" name="regusername" type="text" placeholder="Username" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regpassword">Password</label>
<div class="controls">
<input id="regpassword" tabindex="5" name="regpassword" type="password" placeholder="Password" class="input-large">
</div>
</div>
<div class="controls">
<button id="regsubmit" tabindex="7" name="regsubmit" class="button background-asbestos">Submit</button>
</div>
</div><!-- .span6 -->
<div class="span6">
<div class="control-group">
<label class="control-label" for="reglastname">Lastname</label>
<div class="controls">
<input id="reglastname" tabindex="2" name="reglastname" type="text" placeholder="Lastname" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regemail">Email</label>
<div class="controls">
<input id="regemail" name="regemail" tabindex="4" type="text" placeholder="example#example.com" class="input-large"</td>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regrepeatpassword">Repeat Password</label>
<div class="controls">
<input id="regrepeatpassword" tabindex="6" name="regrepeatpassword" type="password" placeholder="Repeat Password" class="input-large" required>
</div>
</div>
<!-- .span6 -->
<!-- span6 -->
</div><!-- .row-fluid -->
</fieldset>
</form>
Alright your JS and HTML is a big mess of stuff, so I won't recreate it all, but basics:
Give your form an ID:
<form id="SomeForm" name="register" method="POST">
Then prevent default action, and submit if passes:
// reference the button by the ID you gave it
$('#regsubmit').click(function(e){
// stop original submission
e.preventDefault();
// all your checking stuff here, but if true, then:
document.getElementById('SomeForm').submit();
});
This ensures that you are referencing the button correctly, preventing submission correctly, and submitting only if valid.
prevent default action on submit
$('button[name=regsubmit]').click(function(e)
{
e.preventDefault();
//your code below
}

Categories

Resources