Trying to redirect to page on click - javascript

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

Related

How to POST data from client to node server

I am trying to POST the data from a form using a function to node.js server to be inserted into SQLITE. But somehow the data is not posted to the node.js server at all. These are what I have done:
client.js
//function triggered when submit button is clicked
function createInvitation() {
var id = localStorage.getItem('id');
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var refno = Math.floor(Math.random()*89999999+10000000);
//i got all the data here
alert(id + name + phone + email + refno)
if (name == "" || phone == "" || email == "")
{
alert("Please fill in all details!");
}
else {
$.post('/visitors',
{
host_id: id,
visitor_name: name,
visitor_phone: phone,
visitor_email: email,
reference_no: refno
},
function(data) {
alert(data);
window.location.reload();
});
}
}
server.js
app.post('/visitors', function(request,response){
console.log('POST request received at /visitors');
var sql = 'INSERT INTO visitors(host_id, visitor_name, visitor_phone, visitor_email, reference_no) VALUES (?,?,?,?,?)';
var visitors = [request.body.host_id, request.body.visitor_name, request.body.visitor_phone, request.body.visitor_email, request.body.reference_no];
console.log(visitors);
db.run(sql, visitors, function(err) {
if (err) {
console.log("Error: "+err);
}
else {
response.status(200).redirect('generate.html');
}
});
});
Any advises will be greatly appreciated. Thanks in advance
UPDATE:
Is this correct?

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

Function is called but it not shows error for repassword validation. Function is called by onBlur event

function repasswordvalid()
{
var cpassword = document.registration.repassword.value;
var passwordchk = document.registration.password.value;
if((passwordchk != cpassword) && cpassword == "")
{
alert("Cofirm password not matched..!!");
document.getElementById('repassword1').innerHTML = "The password is required.";
document.getElementById('repassword1').focus();
}
else
{
document.getElementById('repassword1').innerHTML = "";
}
}
Here I am checking for confirm password validation onBlur event. All fields are working but here i am stuck.
You probably want an or in your condition not an and, since the cpassword will have to be blank and both field mismatched for the alert to trigger
if((passwordchk != cpassword) || cpassword == "")

function does not always return a value?

I am trying to make this ajax request function work but netbeans is giving a warning that the following function does not always return a value. Can anyone please help.
function fpform(){
var response='';
var fpemail = $('#frgtpwd').val();
//var fpemail = document.getElementById('frgtpwd').value;
if (fpemail == ""){
$('span#fperror').text("insert your emal address");
//document.getElementById('fperror').innerHTML = "Insert your email address";
return false;
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
//document.getElementById('fperror').innerHTML = "Email address is not in valid format";
return false;
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}, function(response){
response = response.trim();
}).success(function () {
if (response == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").hide('<img src="images/ajax-loader.gif" />');
return true;
} else {
alert("your email address was not found");
$("#loader").hide('<img src="images/ajax-loader.gif" />');
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
return false;
}
});
}
}
}
The return true; statement in your code is not returning from fpform. It is instead returning from the callback function given to .success(). By the time this function is executed, the outer function, fpform, has long since returned. The only way to "return" from a function using ajax is with a callback.
Before I give you any code, you've made a bunch of other mistakes:
Your email regex, /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, fails on my email address. + is a valid character as well. Consider not validating email addresses with regex.
$("#loader").hide('<img src="images/ajax-loader.gif" />') does not work. At all. You want $("#loader").empty()
The variable response you declare at the top is shadowed by your argument response in one of your anonymous functions, making response = response.trim() have no effect whatsoever.
function fpform(callback) {
var fpemail = $('#frgtpwd').val();
if (fpemail == ""){
$('span#fperror').text("insert your email address");
callback(false);
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
callback(false);
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}).success(function(response) {
response = response.trim();
if (response == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").hide('<img src="images/ajax-loader.gif" />');
callback(true);
} else {
alert("your email address was not found");
$("#loader").hide('<img src="images/ajax-loader.gif" />');
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
callback(false);
}
}).error(function() { callback(false); });
}
}
}
You should return value after $.post(...).success(...);

Validation of registration form with AJAX and JSON

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.

Categories