Safari hanging when running an ajax function - javascript

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.

Related

I'm having a cannot POST when attempting to submit a form with JS

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

when i click on submit button my email is not send why?

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!

AJax + PHP + MYSQL Newsletter subscriber

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

Unable to Ajax Call Using Jquery

I am trying to do login with the help of Jquery ajax, but at the time of making ajax call using method jQuery.ajax(....) with servlet (Java) this method was unable to call. I am using ajax lib from link http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js.
Every time I am getting the below URL in address bar of browser.
Project/?email=abc88%40gmail.com&password=1234&sendbtn=Send+Message
Below is the Jquery Ajax Code.
$(document).ready(function() {
//global vars
var username=jQuery("#email");
var password=jQuery("#password");
function checkLoginForm() {
if(username.attr("value") && password.attr("value")) {
return true;
} else {
return false;
}
}
jQuery(".txtbar, .txtbox").live("focus", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
var pxlchange = '-45px';
rowbox.addClass('colors');
thelabel.animate({left: pxlchange}, 350, 'linear', function() {});
// The animation is completed
infobox.animate({opacity: 1.0}, 350, 'linear', function() {
// The animation is completed
});
}
jQuery(this).live("keyup", function() {
var theval = jQuery(this).val();
var limitval = 3;
var replacehtml = "";
var emailinfohtml = "Enter a valid e-mail address.";
var subjectinfohtml = "Enter Password.";
if(currid == "email") {
replacehtml = emailinfohtml;
} else if(currid == "password") {
replacehtml = subjectinfohtml;
limitval = 2;
}
// checking against e-mail regex
if(currid == "email") {
if(checkValidEmailAddress(theval)) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(!checkValidEmailAddress(theval)) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
} else {
// we use this logic to check for name+message fields
if(theval.length >= limitval) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(theval.length < limitval) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
}
// now we check if we can display the send button
// much easier to just look for 'good class on the req fields
});
});
jQuery(".txtbar, .txtbox").live("blur", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
rowbox.removeClass('colors');
infobox.animate({opacity: 0}, 400, 'linear', function() {
// The animation is completed
});
});
jQuery("#sendbtn").click(function() {
if (checkLoginForm()) {
jQuery.ajax({
type : "GET",
url : "/DoLogin.htm",data:"userName="+ username.val()+ "&password="+ password.val(),
success : function(msg) {
alert("Ajax Return Success");
return false;
}
});
} else {
alert("Ajax Return Fail Code ");
return false;
}
});
function checkValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+") ([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
HTML code:
<div id="wrap">
<form id="contact-form" name="contact-form">
<div class="rowbox">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" class="txtbar req" tabindex="1">
<div class="infobox">
Enter a valid e-mail address
</div>
</div>
<div class="rowbox">
<label for="subject">Password</label>
<input type="password" id="password" name="password" class="txtbar" tabindex="1">
<div class="infobox">
Enter Password
</div>
</div>
<input type="submit" value="Send Message" id="sendbtn" name="sendbtn" class="submit-button">
</form>
</div>
If you make the data property an object, jQuery will handle parameterizing and URI-encoding it for you automatically. If you insist on it being a string, you need to do all of that yourself.
jQuery.ajax({
type: "GET",
url: "/DoLogin.htm",
data: { userName: username.val(), password: password.val() },
success: function() {
alert("Ajax Return Success");
}
});
On a security note, I wouldn't simply check that the #email and #password fields have value attributes and return true, nor would I transmit plain-text login info over the wire. Maybe you intended this as boilerplate code to get things working and you'll validate/encrypt them better later. :)

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(...);

Categories