Validation of registration form with AJAX and JSON - javascript

I have a Username field in my registration form. When the user hits the Submit button, it should check if the username is not empty and that such username doesn't exist yet. So I have these functions:
function register() {
var userName = checkIsUsernameExist();
var passwordMatch = checkPasswordMatch();
if(userName && passwordMatch){
$.getJSON("inc/API.php",
{
command : "register",
username : $("#txtNewUsername").attr("value"),
password : $("#txtNewPassword").attr("value"),
email : $("#txtEmail").attr("value"),
phone : $("#txtPhone").attr("value")
},
function ()
{
$("#divIsRegFormValid").removeClass("registrationFormAlert");
$("#divIsRegFormValid").addClass("registrationFormConfirm");
$("#divIsRegFormValid").html("Thank you for registering!");
}
);
} else {
$("#divIsRegFormValid").removeClass("registrationFormConfirm");
$("#divIsRegFormValid").addClass("registrationFormAlert");
$("#divIsRegFormValid").html("Some errors occured. Please register again.");
}
}
function checkIsUsernameExist(){
if($("#txtNewUsername").attr("value") == "") {
$("#divIsUsernameExist").html("");
return false;
} else {
$.getJSON("inc/API.php",
{
command : 'isUsernameExist',
username : $("#txtNewUsername").attr("value")
}).done(
function(result)
{
if (result != true){
$("#divIsUsernameExist").removeClass("registrationFormAlert");
$("#divIsUsernameExist").addClass("registrationFormConfirm");
$("#divIsUsernameExist").html("This username is available!");
return true;
} else {
$("#divIsUsernameExist").removeClass("registrationFormConfirm");
$("#divIsUsernameExist").addClass("registrationFormAlert");
$("#divIsUsernameExist").html("This username is not available!");
return false;
}
});
}
}
At this moment I only receive False if the username is empty, and if it's not - I get Undefined (checked it with some Alert commands). So how can I make it work and return True or False if the username is entered and it's been checked if such username already exist or not?
Thank you!

.val() is prefered $("#txtEmail").attr("value") => $("#txtEmail").val() ;)

You get undefined probably because there is no value attribute in your html use $('#txtEmail').val() instead.

Related

Alert popping up multiple times and submit button only working after second click

I am working on my CS50 Final Project. I am designing a web app:
I am using flask.
This happens in the login/register page.
I am trying to check if the username is already taken( through jsonify) and if the password and the password confirmation are equal using JS.
So basically the problem is:
After loading tha page and filling out the register form nothing happens on the first click on the submit button. On the second click everything works just as it is supposed to: the functions run fine and check for matching passwords and if the username is available and alert if necessary. If I then close the alert window and click the submit button again I get two alerts from the usercheck function.
If do the same thing again 3 alerts then 4 and so on....For some reason the function gets called again and again but I can't figure out where....
Here's the HTML:
<form id='register' action='/register' method="POST" onsubmit="return !!(passwordcheck() & usercheck());" ></form>
Here's the two JS function in a script tag in the same page:
function passwordcheck(){
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc){
alert('Passwords do not match')
return false;
}
}
function usercheck(){
$('document').ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r){
if(r == false){
alert('User taken');
$('#username').focus();
}
else{
(document).getElementById('register').submit();
}
} )
})
})
}
And here's the Python code from the application.py file that querys the database for the username:
#app.route("/check", methods=["GET"])
def check():
print(Fore.BLUE + "check function, line 99")
"""Return true if username available, else false, in JSON format"""
username = (request.args.get('username'),)
if username:
c.execute("SELECT username FROM users WHERE username =?", username)
old_user = c.fetchall()
if len(old_user) > 0:
return jsonify(False)
else:
return jsonify(True)
You have defined two handlers for the form submit event:
- the first in the html (onsubmit="return !!(passwordcheck() & usercheck());") is the userCheck function that does not actually make a request
- the second inside the userCheck function ($('form').on('submit',function(e){) that does make a request
So the first time you submit the userCheck function is called, it does not make a request but add a submit event handler to the form. That is why the request is made only after submitting the form a second time.
You should be better off with something like this:
function passwordcheck() {
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc) {
alert('Passwords do not match')
return false;
}
}
function usercheck(handleSuccess, handleError) {
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r) {
if (r == false) {
handleError();
} else {
handleSuccess();
}
})
}
function submit() {
(document).getElementById('register').submit();
}
function handleUserError () {
alert('User taken');
$('#username').focus();
}
$('document').ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
if (!passwordcheck()) {
return;
}
usercheck(submit, handleUserError);
})
})
and without the onsubmit attribute on your form element.

Condition for Insert data into database table

New to Js and stuck here. What should I put into my if statement to insert data into database table? Because right now I do get intended error message when I submit a wrong value but it still inserts it to database. Appreciate the help!
Here is my index.js
var manageMemberTable;
$("#addMemberModalBtn").on('click', function() {
// reset the form
$("#createMemberForm")[0].reset();
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".messages").html("");
// submit form
$("#createMemberForm").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
var form = $(this);
// validation
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
this is what I'm checking
if (firstname == "") {
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
else {
if (firstname.match(/^[a-zA-Z ]+$/) === null){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">Firstname invalid</p>');
}
else {
$("#firstname").closest('.form-group').removeClass('has-error');
$("#firstname").closest('.form-group').addClass('has-success');
}
}
//lastname validation
if (lastname == "") {
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
else {
if (lastname.match(/^[a-zA-Z ]+$/) === null){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
else {
$("#lastname").closest('.form-group').removeClass('has-error');
$("#lastname").closest('.form-group').addClass('has-success');
}
}
And this is the i statement
if( // Something that checks the submitted data meets requirements) {
//submit the form to server
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType : 'json',
This can be one approach.
firstname.match(/^[a-zA-Z ]+$/) returns true if the string matches the regular expression
if ((firstname != "") && (firstname.match(/^[a-zA-Z ]+$/)) &&
(lastname != "") && (lastname.match(/^[a-zA-Z ]+$/))) {
$("#firstname").closest('.form-group').addClass('has-success');
$("#lastname").closest('.form-group').addClass('has-success');
// code to send data to database
}
else {
if(firstname === ""){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
if (!firstname.match(/^[a-zA-Z ]+$/)){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">firstname is invalid</p>');
}
if(lastname === ""){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
if (!lastname.match(/^[a-zA-Z ]+$/)){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
}

validating reCaptcha in javascript function that get called on submit. (ASP classic)

I need help in validating the response of ReCaptcha in javascript validation which is made for other validations like, n Field is empty etc..
The javascript function function verify(f) {....} get called on onSubmit="return verify(this);" in html <form name="form2" method="POST" action="alink.asp" onSubmit="return verify(this);">
Bellow is the complete js function:
function verify(f) {
var msg = '';
var s = f.CKRoutingNumber.value;
s = s.replace(/[^0-9]/gi, "");
f.CKRoutingNumber.value = s;
if (f.CustomerID.value == '') { msg = 'Please enter your Bricks R Us Customer ID.'; f.CustomerID.focus(); }
else if (f.PurchaseOrderNumber.value == '') { msg = 'Please enter the purchase order number.'; f.PurchaseOrderNumber.focus(); }
else if (f.Amount.value == '') { msg = 'Please enter the amount you wish to pay.'; f.Amount.focus(); }
else if (f.CKBankName.value == '') { msg = 'Please enter a value into the Bank Name field.'; f.CKBankName.focus(); }
else if (f.CKRoutingNumber.value == '') { msg = 'Please enter a value into the Routing Number field.'; f.CKRoutingNumber.focus(); }
else if (s.length != 9) { msg = 'Please enter a valid nine-digit routing/transit number.'; f.CKRoutingNumber.focus(); }
else if (f.CKAccountNumber.value == '') { msg = 'Please enter a value into the Account Number field.'; f.CKAccountNumber.focus(); }
else if (f.CKNumber.value == '') { msg = 'Please enter a value into the Check Number field.'; f.CKNumber.focus(); }
else if (f.BillingName.value == '') { msg = 'Please enter a value into the Full Name field.'; f.BillingName.focus(); }
else if (f.BillingAddress.value == '') { msg = 'Please enter a value into the Billing Address field.'; f.BillingAddress.focus(); }
else if (f.BillingCity.value == '') { msg = 'Please enter a value into the Billing City field.'; f.BillingCity.focus(); }
else if (f.BillingState.value == '') { msg = 'Please select a value for the Billing State field.'; f.BillingState.focus(); }
else if (f.BillingZIPCode.value == '') { msg = 'Please enter a value into the Billing ZIP Code field.'; f.BillingZIPCode.focus(); }
else if (f.BillingPhone.value == '') { msg = 'Please enter a value into the Phone Number field.'; f.BillingPhone.focus(); }
if (msg != '') {
alert(msg);
return false;
}
}
The above function is on the same page in which the form is made.
Bellow is the ASP classic code which get response from reCaptcha. Its also on the same page
<%
Dim reresponse
reresponse= Request.form("g-recaptcha-response")
Dim VarString
VarString = _
"?secret=6Lex3CMTAAAAAASVS5XnIq4Ya5ZGvEH_W70NU&" & _
"&response=" & reresponse & _
"&&remoteip=" & Request.ServerVariables("REMOTE_ADDR")
Dim url
url="https://www.google.com/recaptcha/api/siteverify" & VarString
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "POST", url, False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send
Dim ResponseString
ResponseString = objXmlHttp.responseText
Set objXmlHttp = Nothing
If instr(ResponseString, "success" & chr(34) &": true")>0 then
// do nothing
else
// Here I want to get this response message and validate it in the above javascript function.
end if
%>
I'm confused that how can I get the response from asp and validate it in the verify(f) javascript function so that I also get alert message on submit button that the recaptcha is required and or incorrect.
My intention is to validate the reCaptcha response in same veryify javascript function which get called on submit and shows validation in alert()
Remember, both asp code and javascript code are in the same page.
Please ask if you also need my form html code
Your verify() function is running locally and doing some input value checking/alerting is OK, but in any case you should check whatever comes from the browser on de server side. If you would send the ReCaptscha response back to that verify() function you undermine your security because your users could simple change that verify() function ...

return false not working in jQuery ajax

I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.

Trying to redirect to page on click

No expert when it comes to JS/Jquery, but im trying to use this code, and once the registration sign up is done correctly, and the information is stored, instead of a alert box, i wanna have it redirect to another web page... This is what ive got so far, ive tried a few things, but none seem to be working... What am i doing wrong, and how to fix this?
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
if (data == "index.html"){
//...
}
Stripped version.
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
// check if registration ok
location.href = 'index.html';
});
});
});

Categories