I've created a registration form for users to fill in their data and submit for registration. If some fields are empty, a user name is unavailable, or if that user's email is already registered, a warning appears below the submit button, halting their process until their errors are corrected.
Below the email and username input boxes, there is a span id called emailstatus and unamestatus, respectively. If the email or user name is already registered or unavailable, a message is placed within that span informing the user. However, whether the message is shown or not, even if there is nothing wrong with the user's information, the span id status always has the message "Please correct your errors." which can be found in the javascript function signup(). Please help.
HTML:
<p>Enter personal details</p>
//cleaned up code
<input id="email" onfocus="emptyElement('status')" onblur="checkemail()" onkeyup="restrict('email')" maxlength="88" type="text" class="form-control" placeholder="Email"><span id="emailstatus"></span>
<input id="username" type="text" onfocus="emptyElement('status')" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16" class="form-control" placeholder="User Name">
<span id="unamestatus"></span>
<button id="signupbtn" onclick="signup();" class="btn btn-lg btn-login btn-block">Create Account</button>
<span style="font-weight:bold;" id="status"></span>
Javascript: signup()
function signup(){
var u = _("username").value;
var e = _("email").value;
var status = _("status");
if(unamestatus.innerHTML.value != "" || emailstatus.innerHTML.value != ""){
status.innerHTML = "Please correct your errors.";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
location.href = "registration_success.php";
}
}
}
ajax.send("fn="+fn+"&ln="+ln+"&u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
Javascript: checkusername()
function checkusername(){
var u = _("username").value;
if(u != ""){
//_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Javascript: checkemail()
function checkemail(){
var e = _("email").value;
if(e != ""){
//_("emailstatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("emailstatus").innerHTML = ajax.responseText;
}
}
ajax.send("emailcheck="+e);
}
}
Your problem is here:
} else if(unamestatus.innerHTML.value != "" || emailstatus.innerHTML.value != ""){
status.innerHTML = "Please correct your errors.";
}
innerHTML does not have a value property. Use,
} else if(unamestatus.innerHTML != "" || emailstatus.innerHTML != ""){
status.innerHTML = "Please correct your errors.";
}
instead, however there are much better ways of doing this.
Related
I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}
In form post method in MVC view,
if validation fires then loader should not come and display only validations
else no validations fire then loader should come and save the data.
What I have tried:
placed loader on form submit in javascript and disable the button.
$("#frmContact").submit(function (e) {
$(".loading").css("display", "inline");
});
1) loader : Issue is that if validation fires, then loader also come alongwith validations and then need to reload the page and input data.
2) Disable Submit button : If I disable the Submit button on click and if validation fire then after button remains the disable instead enable. So if validation is there then enable the button and if validations are not fire then disable the button.
All this to avoid the duplicate entry as if button enables then if user clicks on submit.
You can do it this way
HTML :
<div id="ajax-loader" style="display:none;">
<img src="<?php echo $loaderSrc; ?>" style="height: 200px;width: 200px;">
</div>
<input type="submit" id = "btnSubmit" value="Submit" name="yt0" onclick="return validateForm();">
In script : (here you can change the fields...i am showing one of my example)
var error_flag = true;
var error_required = true;
$('#btnSubmit').click(function(e){
e.preventDefault();
if(error_flag && error_required){
$("#ajax-loader").css("display", "block");
$('form#login-form').submit();
}
});
function validateForm(){
var user_pass = document.getElementById('LoginForm[user_pass]').value;
var dob = document.getElementById('LoginForm_dob').value;
var re_pass = document.getElementById('re_pass').value;
var user_name = document.getElementById('LoginForm[user_name]').value;
var email = document.getElementById('LoginForm[email]').value;
var tnc = document.getElementById('checkbox1').checked;
// alert(tnc);
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if(user_name == ''){
validate('LoginForm[user_name]','Nick name is required.');
}else if(email == ''){
removeerror('LoginForm[user_name]');
validate('LoginForm[email]','Email is required.');
}else if(!filter.test(email)){
removeerror('LoginForm[email]');
validate('LoginForm[email]','Please enter valid email.');
}else if(user_pass == ''){
// removeerror('LoginForm[email]');
validate('LoginForm[user_pass]','Password is required.');
}else if(user_pass.length < 6){
removeerror('LoginForm[user_pass]');
validate('LoginForm[user_pass]','Min length should be 6.');
}else if(re_pass == ''){
removeerror('LoginForm[user_pass]');
validate('re_pass','Repeat password is required.');
}else if(user_pass != re_pass){
removeerror('re_pass');
validate('re_pass','Password does not match.');
}else if(dob == ''){
removeerror('re_pass');
validate('LoginForm_dob','Dob is required.');
}else{
if(tnc == false){
document.getElementById('tnc_check').innerHTML = 'Please agree Terms and Condition' ;
document.getElementById("tnc_check").style.color = "red";
error_required = false;
}else{
error_required = true;
document.getElementById("tnc_check").style.display = "none";
removeerror('LoginForm_dob');
}
}
}
function validate(id,msg){
document.getElementById(id).style.border='4px solid red';
document.getElementById(id).value = "";
document.getElementById(id).placeholder = msg;
error_required = false;
}
function removeerror(id){
document.getElementById(id).style.border='none';
error_required = true;
}
Check validation on form submit or button submit event using javascript.
if($('#MyForms').valid())
{
// Do something (Valid)
}
else
{
// Do something (invalid)
}
the answer is simple. put valid in the form post event. all is what you want.
$("#frm").submit(function (e) {
if ($(this).valid()) {
$(".loading").css("display", "inline");
}
});
when i click on submit button it will show me the message from the javascript file but it will not go to the php file that i have generated..
here is my html code
<form method="post" id="contactForm" action="email_send.php">
<div class="clearfix">
<div class="grid_6 alpha fll">
<input type="text" name="senderName" id="senderName" placeholder="Name *" class="requiredField" />
</div>
<div class="grid_6 omega flr">
<input type="text" name="senderEmail" id="senderEmail" placeholder="Email Address *" class="requiredField email" />
</div>
</div>
<div>
<textarea name="message" id="message" placeholder="Message *" class="requiredField"></textarea>
</div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
<span> </span>
</form><!-- end form -->
my js file
if ($("#contactForm")[0]) {
$('#contactForm').submit(function () {
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
my php file which i have written on action is
<?php
if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) )
{
$senderName = $_POST['senderName'];
$senderEmail = $_POST['senderEmail'];
$message = $_POST['message'];
if(!empty($senderName) && !empty($senderEmail) && !empty($message))
{
if(strlen($senderName)>25 || strlen($senderEmail)>25 || strlen($message)>50 )
{
echo 'Maximum length reached for each field';
}
else
{
$to = 'info#courtpiece.com';
$subject = 'Court Piece Rung';
$body = "Name:".$senderName."\n"."Message: ".$message;
$header = 'From'.$senderEmail;
if(#mail($to,$subject,$body,$header))
{
echo 'Thanks for Contacting Us.We\'ll in touch soon. ';
}
else
{
echo 'Sorry an error occured ';
}
}
}
else
{
echo 'All fields are required. ';
}
}
?>
Sometimes this can create a problem..
You are using: if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) ){
instead of:
if(isset($_POST['sendMessage'])){
if(!empty($_POST['senderName']) && !empty($_POST['senderEmail'])){
CODE HERE
}
}
If not, then probably you miss-confiugred your email sending service.
try a test on the email sending.
mail()
You will need to supress the default behaviour of your form so it doesnt also send a request to your server. You do this by calling the prevendDefault function of your event parameter .submit(function(e)....
if ($("#contactForm")[0]) {
$('#contactForm').submit(function (e) {
e.preventDefault(); //to suppress the behaviour of your Form -> you will send data manually with $.post
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post("email_send.php", formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
I have to say that there is room for improvement in the way you have built up this validation.
Try running the form again with the additions I made.
Report back!
I have a registration form that onsubmit runs a validation javascript function to check that
a:all the boxes have a value in them.
b:the password values match.
c: the email address is valid.
The email validation script makes an ajax call to check to see if the email address has been registered before.
It runs great in all browsers except Safari. In Safari it just hangs the page.
Heres the relevant parts of the code:
html form
<form name="login" action="<?php echo htmlspecialchars($pre_link.'register3.php'); ?>" method="post" onsubmit="return validateReg();">
<div id="register_label">Email Address:<span id="req">*</span></div>
<input class="register_input" id="myregusername" name="myusername" size="14"/><br><br>
<div id="register_label">Password:<span id="req">*</span></div>
<input class="register_input" id="mypassword" name="mypassword" size="14" type="password"/><br><br>
<div id="register_label">Confirm Password:<span id="req">*</span></div>
<input class="register_input" id="mypassword1" name="mypassword1" size="14" type="password"/><br><br>
<br /><br />
<input type="submit" id="loginBtn" name="submit" value="Next" />
</form>
the js validation code
function validateReg(){
var origBorder = "1px solid #CCCCCC";
var errorBorder = "1px solid red";
var myregusername = document.getElementById("myregusername");
var mypassword = document.getElementById("mypassword");
var mypassword1 = document.getElementById("mypassword1");
var errorstr = "";
var error = false;
myregusername.style.border = origBorder;
mypassword.style.border = origBorder;
mypassword1.style.border = origBorder;
if(myregusername.value.length == 0) {
errorstr = errorstr + "\n" + "Please enter your email address";
error = true;
myregusername.style.border = errorBorder;
}
if(mypassword.value.length<=5) {
errorstr = errorstr + "\n" + "Please enter your password that is at least 6 characters long";
error = true;
mypassword.style.border = errorBorder;
}
if(mypassword1.value!=mypassword.value) {
errorstr = errorstr + "\n" + "Your passwords do not match";
error = true;
mypassword.style.border = errorBorder;
mypassword1.style.border = errorBorder;
}
if(error) {
alert(errorstr);
return false;
} else {
if (checkMail()){
return true;
} else {
return false;
}
}
}
ajax code
function checkMail(){
var myusername = document.getElementById("myregusername") ;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(myusername.value)) {
function checkMail3(){
var myusername = document.getElementById("myregusername").value ;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(myusername)){
$.ajax({
url: "checkregemail.php",
type: "post",
headers: { "cache-control": "no-cache" },
data:{ username : myusername },
success: function(data) {
if(data=='1'){
alert("sorry this email address has already been registered\nClick login to sign in with his email address");
document.getElementById("myregusername").focus();
return false;
}else{
alert("good email address");
return true;
}
},
error:function(){
alert("failure");
}
});
} else {
var errorBorder = "1px solid red";
var error = false;
alert('Please enter a VALID email address');
myusername.style.border = errorBorder;
return false;
}
}
} else {
var errorBorder = "1px solid red";
var error = false;
alert('Please enter a VALID email address');
myusername.style.border = errorBorder;
return false;
}
}
If I remove the ajax call, then it runs fine in Safari.
I have read about Safari caching $post's but I don't have enough knowledge to be able to incorporate what I have found into my code and get it working. I have added the 'headers: { "cache-control": "no-cache" }, ' but that still doesnt fix the issue.
if the email is registered then it throws the error message but if the email is not found in the db, it throws the 'emailk good' alert but doesnt return the true to the original statement so the form does not get submitted
Any help would be greatly appreciated.
Currently I am able to add a new email address to my newsletter table, however I am struggling with the AJAX part of the query, ie. the validation.
Below is my Signup.php file:
<?php
require_once('required/init.php');
require_once('required/settings.php');
require_once('required/database.php');
require_once('required/class.phpmailer.php');
require_once('required/globals.php');
$email = trim($_REQUEST["email"]);
// Check if subscriber exists
$SQL= "select email from tblnewsletter where email='".$email."'";
$result = mysql_query($SQL);
if(!$result) {die('Problem in SQL: '.$SQL);} //just checking if there was a problem with your query
if (mysql_num_rows($result)==1) { // he was subscribed already
echo 'You are subscribed.'; // Change the message if you want.
}
else { // does not exist ==> add to the table
$SQL2= "INSERT into tblnewsletter (email) VALUES ('".$email."')";
mysql_query($SQL2);
echo 'Thank you for subscribing'; // Change the message if you want.
}
?>
and here is my Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#nlsubmit').on('click', function() {
signup();
return false;
});
});
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function signup()
{
var emailentered = $("#email").val();
var email = trim(emailentered);
//EMAIL VALIDATION
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
var apos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
lastpos = email.length - 1;
var badEmail = (apos < 1 || dotpos - apos < 2 || lastpos - dotpos < 2);
if (email == "" || !goodEmail || badEmail)
{
//Email address fails
$('myResponse').style.display = 'inline';
$('myResponse').style.color = 'red';
alert('Please enter a valid email');
$('email').focus();
return false;
}
else
{
email = encodeURIComponent(email);
//Email address succeeds
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
}
}
function showResponse(req) {
$("loading").hide();
$("myResponse").innerHTML = req.responseText;
$("myResponse").style.display = "inline";
$("myResponse").style.color = "blue";
$("submit").show();
$("email").invoke('clear');
}
function showException(req) {
$("myResponse").innerHTML = req.responseText;
alert("An error occured while talking to the server. Please try again.");
$("loading", "myResponse").invoke('hide');
$("submit").show();
$("email").invoke('clear');
}
</script>
The form that is calling all this is as follows:
<form method="post" name="subform" id="subform" action="">
<input type="text" id="email" name="email" value="">
<input type="submit" id="nlsubmit" name="submit" value="Sign up">
<div id="myResponse" style="display:none;"></div>
<div id="loading" style="display:none;"><img src="/images/wait.gif" alt=""></div>
</form>
Like I said the newsletter table is updated great, though I'm needing the user to be notified on the same page if they are already present, if the email is invalid etc.
In your function:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
'result' refers to whatever was echoed on signup.php, so if result=="You are subscribed." that means that the email address already exists in the database, otherwise if result=="Thank you for subscribing" the email address is new to the database and the new user subscribed. So the function should look something like this:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
if(result=="You are subscribed.")
{
// notify user that email address already exists
}
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});