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(...);
Related
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.
Validate form has been working fine but I have now tried adding email validation to the code and now nothing will validate, form submits without any popup error boxes.
Here's The Current Code:
<script type="text/javascript">
function validateForm(){
var a=document.forms["order_form"]["fname"].value;
var b=document.forms["order_form"]["address"].value;
var c=document.forms["order_form"]["city"].value;
var d=document.forms["order_form"]["pcode"].value;
var e=document.forms["order_form"]["email"].value;
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
if (a==null || a=="")
{
alert("Full name must be filled out");
return false;
}
else if (b==null || b=="")
{
alert("Address must be filled out");
return false;
}
else if (c==null || c=="")
{
alert("City must be filled out");
return false;
}
else if (d==null || d=="")
{
alert("Post-Code must be filled out");
return false;
}
else if (e==null || e=="")
{
alert("Email Address must be filled out");
return false;
}
else if (atpos<1||dotpos<atpos+2||dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
Form is likely submitting due to the following errors
Change:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
To
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
indexOf() returns a number not an object so there is no value property.
Also as noticed by #fpierrat email should be e
I don't see any declaration for email before following:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
Maybe you meant e, not email?
Also delete the .value after indexof() calls, see #charlieftl's answer, we were quite complementary on this ;-)
I have this partially working code. What it suppose to do is to check for existing email address in database. If no email exist then return true;
$(document).ready(function() {
var email_check = 0;
var checking_html = '<img src="http://i.imgur.com/Y8wXAZp.gif" /> Checking...';
var characters_error = 'Minimum amount of chars is 6';
//when button is clicked
$('.register').click(function(){
//run the character number check
if($('#email').val().length < 1){
$('#email_result').html(characters_error);
return false;
}
else{
//else show the cheking_text and run the function to check
$('#email_result').html(checking_html);
alert(check_email_availability());
}
});
});
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
email_check = 1;
}else{
email_check = 0;
}
});
if (email_check == 1){
return true;
}else{
return false;
}
}
Now, the problem is if current state is false, when I enter an email that is not available in the db and click button, I still get false alert, and when the next time I click button I get true alert. For some reason the function execute bottom code first (checking email_check value) and after that it execute the function. Why is that? What is wrong with my code? How can I make it execute function and then check the email_check value whether 1 or not?
I would change this to put an ajax success callback on your check function something along the lines of.
success: function (data, status, xhr ) {
myFunctionShowEmailSuccess();
},
error: function (xhr, status, error) {
myFunctionShowEmailFailure();
}
Try doing this.
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
return true;
}else{
return false;
}
});
}
For proper registration, user is required to enter password two times and password in both these textboxes should match.
However, on validating this using this code, JavaScript is not showing alert dialog.
Here pswrd and pswrd1 are two textboxes of password type.
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message+="\nPasswords did not match";
result=false;
}
if(!result)
{
alert(message);
}
Try this
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message = "Passwords did not match";
result=false;
}
else {
result = true;
}
if(!result)
{
alert(message);
}
Try this code.
if(pswrd.value!== pswrd1.value)
{
alert("Password does not matched!");
return false;
}
Hope this help :)
if(pswrd.value !== pswrd1.value)
the text in bold above should be != and not !==
!== is not an operator, use == for equality and != for unequality
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.