JS authentication for HTML page - javascript

I want to add a basic name and email validation JS script to an HTML page, so when submit is pressed it will check multiple fields and throw errors if any are filled incorrectly. Unfortunately, when submit is pressed the page just reloads with fields empty and no error is thrown on the HTML page.
I am still learning JS.
Here is my JS snippet to check for name and email:
//Check if name is anything other than letters or spaces. If it isn't throw error.
function validateForm() {
var validEntry = /[a-zA-Z ]/;
var x = document.forms["clientinfo"]["txtFullName"].value;
if (x.value.match(!validEntry)) {
alert("Invalid name. Please try again.");
document.clientinfo.txtFullName.focus();
return false;
}
// Check if email is in proper format - words#words.com. If it isn't throw error.
var y = document.forms["clientinfo"]["txtEmail"].value;
var validEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})/
if (y.value.match(validEmail)) {
return true
} else {
alert("Invalid email. Please try again.")
document.clientinfo.txtEmail.focus();
return false;
}
}
<div id="inputArea">
<form name="clientinfo" onsubmit="return validateForm()" method="post">
Name:
<input class="Inputinfo" type="text" name="txtFullName" placeholder="John Stewart" required>
<br> Email:
<input class="Inputinfo" type="text" name="txtEmail" placeholder="john#example.com" required>
<br> Phone:
<input class="Inputinfo" type="tel" name="phone" placeholder="XXX-XXX-XXXX" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
<br> Description:
<br>
<textarea class="Inputinfo" id="txtDescription" name="description" rows="8" cols="50" placeholder="Please enter any additional client information here."></textarea>
<br>
<input type="submit" value="Enter" id="enterbutton">
</form>
</div>
How can I fix this problem?

!validEntry is false, so you're testing x.value.match(false) in your first if statement. What you want is if (!x.value.match(validEntry)) and you have to change the regexp to match the entire input string (it currently looks for a match of the valid characters anywhere in the input.
x.value and y.value should just be x and y. You already used .value when you assigned the variables, so they contain strings, not the input elements.
To make it easier to keep adding more validations, don't do return true when the email is valid. Put that at the end of the function, and just do return false in each of the invalid cases.
//Check if name is anything other than letters or spaces. If it isn't throw error.
function validateForm() {
var validEntry = /^[a-zA-Z ]+$/;
var x = document.forms["clientinfo"]["txtFullName"].value;
if (!x.match(validEntry)) {
alert("Invalid name. Please try again.");
document.clientinfo.txtFullName.focus();
return false;
}
// Check if email is in proper format - words#words.com. If it isn't throw error.
var y = document.forms["clientinfo"]["txtEmail"].value;
var validEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})$/
if (!y.match(validEmail)) {
alert("Invalid email. Please try again.")
document.clientinfo.txtEmail.focus();
return false;
}
return true;
}
<div id="inputArea">
<form name="clientinfo" onsubmit=" validateForm(); return false" method="post">
Name:
<input class="Inputinfo" type="text" name="txtFullName" placeholder="John Stewart" required>
<br> Email:
<input class="Inputinfo" type="text" name="txtEmail" placeholder="john#example.com" required>
<br> Phone:
<input class="Inputinfo" type="tel" name="phone" placeholder="XXX-XXX-XXXX" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
<br> Description:
<br>
<textarea class="Inputinfo" id="txtDescription" name="description" rows="8" cols="50" placeholder="Please enter any additional client information here."></textarea>
<br>
<input type="submit" value="Enter" id="enterbutton">
</form>
</div>

Related

JQuery Validation Working, but submitHandler is not

I have a form I am trying to validate using JQuery Validate, which works fine. When the submit button is clicked, the submitHandler should 1. disable the button (to prevent multiple submissions) and 2. change the button text.
As is, the code works for validation but does not invoke the submitHandler.
I've looked over many threads on here, saying that the button must be type="submit", inside the <form> tags, etc. and cannot figure this out. The button is still able to be clicked multiple times.
Any help?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address : {
required: true
},
city : {
required: true
},
state : {
required: true
},
zipcode : {
required: true
},
phoneNumber : {
required: true,
phoneUS: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required : "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function (form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
form.submit();
}
});
});
</script>
<!DOCTYPE html>
<html lang="en">
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br>
Address:<br>
<input type="text" name="address" class="required" placeholder="Please enter your address."/><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc."/><br>
<br>
City:<br>
<input type="text" name="city" class="required" placeholder="Please enter your city."/><br>
<br>
State:<br>
<input type="text" name="state" class="required" placeholder="Please enter your state."/><br>
<br>
Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode."/><br>
<br>
Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number."/><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="submit" value="final" >CONTINUE</button>
</form>
</div>
</html>
You can do your validation and disable the button on click event of button, at client side.
<script type="text/javascript">
$("#finalSubmit").click(function()
{
//do your validation and if correct then disable the button
$("#finalSubmit").attr("disabled", true);
//other work if any
}
);
</script>
1st of all instead of making validations with jQuery, make validations on server side like with PHP etc., and reflect the output on the display page.
An example here:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Site Title</title>
</head>
<body>
<h1>Form</h1>
<div class="message"></div>
<form method="post" action="" name="registrationForm">
First Name <input type="text" name="fname"><br>
Last Name <input type="text" name="lname"><br>
Phone <input type="text" name="phone"><br>
<input type="submit" value="Register" class="regbtn">
</form>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".regbtn").click(function(){
var form = document.registrationForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: "your-processing-page.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".regbtn").prop('disabled', true).val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
$(".regbtn").prop('disabled', false).val('Register');
}
});
return false;
});
});
</script>
</body>
</html>
your-processing-page.php
<?php
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$lname = (!empty($_POST['lname']))?$_POST['lname']:null;
$phone = (!empty($_POST['phone']))?$_POST['phone']:null;
if($_POST){
// Perform Checks Here
if(trim($fname) == ''){
echo "Please enter first name.";
}else if(trim($lname) == ''){
echo "Please enter last name.";
}else if((strlen($phone)) == 0){
echo "Please enter a phone number";
}else if((strlen($phone)) < 10){
echo "Phone number must not contain less than 10 digits.";
}else if((strlen($phone)) > 10){
echo "Phone number must not contain more than 10 digits.";
}else{
// If all checks are cleared perform your query
$stmt = $pdo->prepare("INSERT INTO members(mem_fname, mem_lname, mem_phone)VALUS(:fname, :lname, :phone)");
$stmt-> bindValue(':fname', $fname);
$stmt-> bindValue(':lname', $lname);
$stmt-> bindValue(':phone', $phone);
$stmt-> execute();
if($stmt){
echo "Success! User has been registered.";
}else{
echo "Sorry, something went wrong. Please refresh the page and try again!";
}
}
}
?>
That's a complete answer. Here:
Validation is done on server side using PHP (better method and must be followed).
jQuery disables submit button to prevent double submission after click.
jQuery changes button text value when submit button is pressed and changes back to default on successful return from form submission.
Note: The above is a fully working "standard" coding sample. That's how you should code. However, perform other necessary checks as per your need. Take the above coding only as a sample to frame your own code. Happy coding :)
Change the submit button name to something else because it overrides the submit() function on the form, then this code should work for you(Reference). ↓↓
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address: {
required: true
},
city: {
required: true
},
state: {
required: true
},
zipcode: {
required: true
},
phoneNumber: {
required: true,
// phoneUS: true,
digits: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required: "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function(form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
setTimeout(function() {
form.submit();
}, 3000);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br> Address:
<br>
<input type="text" name="address" class="required" placeholder="Please enter your address." /><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc." /><br>
<br> City:
<br>
<input type="text" name="city" class="required" placeholder="Please enter your city." /><br>
<br> State:
<br>
<input type="text" name="state" class="required" placeholder="Please enter your state." /><br>
<br> Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode." /><br>
<br> Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number." /><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="save" value="final">CONTINUE</button>
</form>
</div>
</html>

Javascript - A problem with the validation of my form

I have a problem with the validation script of my php form to send an email, and although it works very well to validate the form, when the user clicks on the "accept" button of the alert, the script does not block the action, and the form is sent anyway...
What am I doing wrong?
Thanks in advance!
HTML:
<div id="form">
<section>
<form action="send.php" method="post" accept-charset='UTF-8'>
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">
</div>
</form>
</section>
</div>
SCRIPT (validation):
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
}
Change the event to onsubmit and put it on the form.
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
console.log('passed!');
}
<div id="form">
<section>
<form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND">
</form>
</section>
</div>

Pop-up messages during registration

recently started to deal with javascript, now I'm doing a registration page. And at the moment the notification about the incorrect filling of the form is displayed via alert (). How can this be improved so that if you enter incorrectly, you immediately see a hint ?
function valid(form){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker = "Wrong first name";
}else if(!namePattern.test(lName)){
checker = "Wrong last name"
}else if(!passwordPattern.test(password)){
checker = "Wrong password"
}else if(confirmPassword != password){
checker = "Your passwords do not match"
}else if(!emailPattern.test(email)){
checker = "Wrong email"
}
if(checker){
alert(checker);
}
}
<form action="" method="post" name="submit" onsubmit="valid(this)">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" value="submit"/>
</form>
I will be grateful for help)
I suggest you put on input elements onchange function, for example:
<input type="text" name="fName" id="fName" placeholder="Your first name" onchange='validateInput(e)'>
And then you check in function:
function validateInput(e){
var namePattern = new RegExp("^([A-z]{4,20})$");
const value = e.target.value;
if(!namePattern.test(value)){
alert("Wrong first name");
// But instead of alert I would suggest you change the color of the input element in order for the user to see real time that he is entering wrong thing.
//When he enters correct data, input border should be green. This is much more user friendly
}
}
You can every validation check separately like this...
function firstname(value){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
if(!namePattern.test(value)){
checker = "Wrong first name";
}
if(checker){
alert(checker);
}
}
<input type="text" name="fName" id="fName" placeholder="Your first name" onblur="firstname(this.value)">
I suggest you can use jquery validation.
The thing is, you are checking your form on your submit event (which is obviously the event that is trigger when the form is submitted).
You need to add input validation on each of your input fields via certain event listeners.
If you add onchange event listener, your callback validation will fire each time you move your focus to another element (aka blur event).
If you add oninput event listener, your callback validation will fire each time you type something new.
I would recommend taking a look at the answers of this question.
var checker;
function valid(form){
checker = '';
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker += "No first name<br/>";
}
if(!namePattern.test(lName)){
checker += "No last name<br/>"
}
if(!passwordPattern.test(password)){
checker += "No password<br/>"
}
if(confirmPassword != password){
checker += "Your passwords do not match<br/>"
}
if(!emailPattern.test(email)){
checker += "No email<br/>"
}
if(checker){
document.getElementById("hint").innerHTML = checker;
}
}
valid(document.getElementById("form"));
<form id='form' action="return false;" method="post" name="submit" oninput="valid(this)" onsubmit=' return false;'>
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div style='color:red' id='hint'></div>
<input type='submit'/>
</form>
Using the oninput event to run every single time a input is changed. More user friendly by displaying a text tip instead of popups, and shows all errors, not just the first one in the if/elseif loop.
P.S: You seem to have forgotten to add the submit button in your code.
EDIT: Also made it check validation as soon as the page loaded up too.

Redirecting a form with multiple submit inputs

I have a form which has 3 separate input with a type of "submit".
The first two inputs output a message once they are clicked, but the final one is supposed to redirect to another page however it is not doing this. I think this is because the form is submitting and refreshing the page before it gets to the JavaScript for redirection.
Here is my code:
FORM.php
<form class="form" id="form" method="POST" enctype="application/x-www-form-urlencoded">
<br>
<input type="email" name="email" id="email" maxlength="80" value="<?php echo $email ?>" placeholder="Enter Your Email" /><br /><br>
<input id="button4" type="submit" value="Get Security Question" name="submit2" style="cursor:pointer;"/><br>
<br><input type="password" name="securitya"id="securitya" maxlength="20" value="<?php echo $securitya ?>" placeholder="Enter Your Security Answer" /> <br />
<br>
<input id="button3"type="submit" value="Check Answer" name="submit" style="cursor:pointer;"/>
<br>
<br><input type="password" name="newpassword" id="newpassword" maxlength="20" placeholder="Enter Your New Password" /> <br />
<br><input type="password" name="confirmpassword" id="confirmpassword" maxlength="20" placeholder="Re-Enter Your New Password" /> <br />
<br>
<input id="button2" type="submit" value="Change Password" disabled="disabled" name="submit" style="cursor:pointer;"/>
JavaScript
jQuery(function(){
$("#button2").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#newpassword").val();
var checkVal = $("#confirmpassword").val();
if (passwordVal == '') {
$("#newpassword").after('<span class="error" >Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#confirmpassword").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (passwordVal != checkVal ) {
$("#confirmpassword").after('<span id = "pass" class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) { return false; }
else {
$("#button2").after('<span class="error">Passwords accepted.</span>');
window.location.href='adminsignin.php';
}
});
});
What is weird about this is the message 'Passwords accepted' appears on screen for a split second, but there is no redirection to 'adminsignin.php'
Can anyone help?
In your javascript, pass the event into the click handler, and preventDefault().
$("#butotn2").click(function(e) {
e.preventDefault();
...
}
the submit button has default behavior, so you'll want to prevent its default behavior so that you can perform your operations and then redirect with your window.location.href.
please try changing to document.location = 'your URL';

Validate form, check if user exists, register them. All with Ajax

My javascript is inside an html file called register.html.
The user submits the form. This should then trigger the $('input[name="createacc"]').click(function (e) AJAX then sends those 4 variables to checkuser.php. Checkuser.php should then check to see if the username exists. If it does exist, it should echo 0. If it does not exists, it should echo 1. Register.html then checks to see what checkuser.php echoed. If the echo was "0" then, then an alert box should appear saying username unavailable. If the echo was "1" or anything else, register.html should run $("#registerform").submit(); which then does the php script. This should all happen without leaving the register.html page.
I check chrome's built in debugger and I see that if the account exists checkuser.php writes back 0 and if the account doesn't it writes back 1. But for some reason nothing else happens. The account does not register nor do I get an alert box saying the username is unavailable
here is my register.html
<form ata-parsley-validate name="registerform" id="registerform" action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input name="firstname" id="firstname" maxlength="32" type="text" placeholder="Optional" />
</p>
<p>
<label for="username" id="usernameText">Username:</label>
<input data-parsley-pattern="^[A-Za-z0-9_]{3,15}$" data-parsley-length="[3, 15]" name="username" id="username" maxlength="32" type="text" data-parsley-error-message="Username needs to be between 3 and 15 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password1">Password:</label>
<input name="password1" id="password1" data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" data-parsley-length="[5, 25]" type="password" data-parsley-equalto="#password2" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password2">Confirm Your Password:</label>
<input name="password2" id="password2" data-parsley-length="[5, 25]" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" type="password" data-parsley-equalto="#password1" required/>
</p>
<p>
<label for="email">E-Mail:</label>
<input data-parsley-trigger="change" name="email" id="email" maxlength="1024" type="email" required/>
</p>
<p>
<input type="submit" id="submit" class="submit" name="createacc" value="Register" />
</p>
</form>
Here is my javascript
<script>
$(document).ready(function () {
$('input[name="createacc"]').click(function (e) {
var username = $('input[name="username"]').val();
var firstname = $('input[name="firstname"]').val();
var password1 = $('input[name="password1"]').val();
var email = $('input[name="email"]').val();
e.preventDefault();
$.ajax({
type: 'POST',
data: {
username: username,
firstname: firstname,
password1: password1,
email: email
},
url: 'checkuser.php',
success: function (data) { //Receives the data from the php code
if (data === "0") {
alert("Username Unavailable");
} else {
$("#registerform").submit();
alert("Account successfuly created");
}
},
error: function (xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
Update - I have fixed parts of my code through the help of others below me. My only issue now is that $("#registerform").submit(); doesn't do anything
You are trying to return and JSON not setting
header('Content-type: application/json');
Decide whether you want to pass plaintext or json. Your string might be now "0", not 0
Try
if (data === '"0"') {
I think the problem is in your success.you have written If it does exist, it should echo 0. If it does not exists, it should echo 1.you should use:
success: function (data) { //Receives the data from the php code
if (data == '"0"') { //register if user exists.
$("#registerform").submit();
} else {
alert("Username Unavailable");
}

Categories

Resources