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

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

Related

JS authentication for HTML page

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>

Sending form data to Parse.com

I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>
This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});

Form validation in HTML5 doesn't work

Hi Could you please have a look at my HTML and function? The required field doesn't work. Any ideas why?
<form action='contact_form.php' method='post' class="contactForm">
<div class="formSecWrap">
<input type="text" class="formField" title="Name" id="name" name="name" value="" required/>
<input type="text" class="formField" title="Email" name="email" id="email" value="" required/>
<input type="text" class="formField" title="Phone" name="phone" id="phone" value="" required />
<input type="text" class="formField" title="Date & Time" name="date" id="date" value="" required/>
</div>
<div class="formSecWrap formSecWrap2">
<textarea class="textarea formField" title="Message" name="message" id="message"></textarea>
</div>
<input class="button" id="submit-form" type="submit" name="submit" value="Send Message" />
<div id="success">
</div>
</form>
And here is my function. I am not sure why it doesn't pick it up as a required fields.I have not created this form myself but was trying to work it out somehow.
Thank you
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
date = $('#date').val(),
message = $('#message').val(),
data_html,
success = $('#success');
if(name == "")
$('#name').val('Please enter your name.');
if(phone == "")
$('#phone').val('Please enter your phone number.');
if(date == "")
$('#date').val('Please enter a date and time.');
if(email == ""){
$('#email').val('Your email is required.');
}else if(reg.test(email) == false){
$('#email').val('Invalid Email Address.');
}
if(message == "")
$('#message').val('Message is required.');
if(message != "" && name != "" && reg.test(email) != false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&phone="+ phone + "&date="+ date;
//alert(data_html);
$.ajax({
type: 'POST',
url: '../contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#date').val('');
$('#message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
});
try to pass arguments to you anonymous function
(function($){
//all that code
})(jQuery);
You can try executing the anonymous function something like:
(function($){
//Your code
}.call(this));
Please create the fiddle if the problem does not get resolved
anonymous function should be called for execution:
(function($){
//your code
})(jQuery);
for calling anonymous function use () right after the function ends, and pass jQuery parameter.
Remove the first and the last lines from your javascript.
(function($){
and
});
It wraps the code into an anonymous function which isn't invoked so you don't bind the click event to the submit button.
its working fine in both firefox and chrome..
Still if does not work you can check this out
HTML form required command not working?

validating login form with php and javascript

These gets the username and password inputted by the user and is expected to be sent to the validate.php file to check whether the records is present in the database or not. and receives a response.
<script type="text/javascript">
function validatelogin() {
var user=document.forms["login"]["username"].value;
var pass=document.forms["login"]["password"].value;
if(user==null || user=="") {
alert("Please enter username");
$('#username').focus();
return false;
} else if(pass==null || pass=="") {
alert("Please enter password");
$('#password').focus();
return false;
} else if(user!==null || user!=="" || pass!==null || pass!=="") {
// These gets the username and password inputted by the user and is
// expected to be sent to the validate.php file to check whether the
// records is present in the database or not. and receives a response.
$.ajax({
url : "validate.php",
type : 'POST',
data : $('#login').serialize(),
success : function(msg) {
$('#login-box').html(msg);
}
});
return false;
} else {
alert("form submitted");
}
}
</script>
php file-used in querying the database to check existing records and is expected to trigger true or false response back to the ajax -please how can i do this.then from there the code can now decide whether to log in or not.
<?php
error_reporting(0);
mysql_pconnect("localhost","root","");
mysql_select_db("sim_tracker");
$username=$_POST['username'];
$password=$_POST['password'];
mysql_query("select * from tbl_user where
username='$username' and password='$password'");
$row=mysql_affected_rows();
if($row>0) {
return false;
echo"$username,$password";
}
?>
html
<div id="login-box" class="login-popup">
<a href="#" class="close">
<img src="images/close_pop.png" class="btn_close"
title="Close Window" alt="Close" />
</a>
<form method="post" id="login" class="signin"
action="#" onSubmit="return validatelogin()">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value=""
type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value=""
type="password" placeholder="Password">
</label>
<button class="submit button" type="submit">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
I see at least 2 issues in your code:
mysql_affected_rows() will not refer to a select query, you're looking for mysql_num_rows()
your echo statement will never be executed because there's a return in front of it, so your script will in both cases (either the login information was correct or not) return absolutely nothing. So here's some better code:
$result = mysql_query("select * from tbl_user where username='$username' and password='$password'");
$row_count = mysql_num_rows();
if ($row_count > 0) {
// login correct, add some code to actually log the user in (i. e. some session stuff)
echo "You were logged in!"; // if you want just true or false say echo 1 instead
}
else {
// login incorrect
echo "Wrong username or password!" // or again echo 0
}

Can't submit my form twice with ajax

Hey everyone, I have some problems with a (I think simple) form submitting with ajax.
The first time the user submit the form, everything goes OK: The content of the div changes and the php is processed. But if there is no match in my DB it will return "f" and the javascript will write back an unusable form that can't be re-submitted with ajax.
The HTML:
<div class="maincontainer" id="login">
<form id="loginform" onsubmit="void login();return false;">
<input name="username" type="text" class="textboxinput" id="username" autocomplete="off" />
<input name="password" type="password" class="textboxinput" id="password" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
</form>
</div>
The Javascript:
function login(){
//Change the box content to "Logging in"
$("#login").html("<p style='line-height:170px;text-align:center;width:100%;margin:0px;padding:0px;'>Logging in</p>");
//Get the values of the username and password field
var username = $('#username').val();
var password = $('#password').val();
//Make the ajax request
$.ajax({
datatype: "text",
type: "POST",
url: "process.php",
data: "username=" + username + "&password=" + password,
success: function (m) {
//If there's no match, rewrite the form in the div
if ( m == "f"){
content= " <form id='loginform' onsubmit='void login();return false;'><input name='username' type='text' class='textboxinput' id='username' autocomplete='off' /><input name='password' type='password' class='textboxinput' id='password' autocomplete='off' /><input type='submit' name='button' class='button' id='button' value='Login' /> <p style='font-size:small;'>Login failed, please try again</p></form>";
$("#login").html(content);
}
}
});
};
EDIT
I didn't find the problem but I did find a solution which is not to erase my form, only hide it
HTML:
<div class="maincontainer" id="login">
<div id="errorbox"></div>
<form id="loginform" onsubmit="return login();">
<input name="username" type="text" class="textboxinput username" id="username" value="username" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='username'" autocomplete="off" />
<input name="password" type="password" class="textboxinput password" id="password" value="password" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='password'" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
<div id="errorshow">RegisterForgot your login infos?</div>
</form>
</div>
Javascript:
function login(){
var username = $('#username').val();
var password = $('#password').val();
//Do security checks here
$("#loginform").hide();
$("#errorbox").html("<p class='logloading'>Logging in</p>");
$.ajax({
datatype: "text",
type: "POST",
url: "login.php",
data: "username=" + username + "&password=" + password + "&method=js",
success: function (m) {
if ( m == "f"){
$("#errorbox").html("");
$('#username').val("");
$('#password').val("");
$("#loginform").show();
$("#errorshow").html("<p class='errormsg'>Wrong username/password combination</p>");
$("#username").focus();
}
else{
window.location = m;
}
}
});
return false;
};
Oh, and I should thank everybody that commented here (and posted) every info helped me a bit.
Just a fix, not an explicit answer to your original question.
I'd use
data: $('#form_id').serialize()
instead of manually doing all of this:
data: "username=" + username + "&password=" + password,
What happens when the user submits a space? Your query breaks.
Just make sure the username box has a name of username and the password box follows the same pattern.
EDIT
This code is a bit odd:
onsubmit='void login();return false;'
Instead of manually inputting this, try this code (just delete that part and insert this):
$('#loginform').live('submit', function(e) {
login();
e.preventDefault()
});
I think I ran into this problem a while back as well.
A plausible workaround would be to put the login function on the onclick of the submit button instead (and have that return false as well)

Categories

Resources