I am facing the unexpected behavior of javascript function. Im an passing the ID of a field as string to function but it is receiving as bool value. Please help the code is below.
Function
function page_smooth_scroll(target_id) {
if (target_id =! null) {
$j('html, body').animate({
scrollTop: $j("#" + target_id).offset().top - 120
}, 500);
}
}
calling function
function validatePassword(){
var validPassword = false;
var pwd = $j("#Password").val().trim();
var cfmPwd = $j("#ConfirmPassword").val().trim();
if((pwd == "") || (cfmPwd == "")){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Please enter Password</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
if(pwd != cfmPwd){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Password does not match</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
validPassword = true;
}
}
return validPassword;
}
the image is below while debugging
passing string
receiving bool
if (target_id =! null) {
I think you mean a != b
Because a=!b means a = !b which means "assign the opposite boolean value", which will indeed turn anything into a boolean.
Next time if you think a function is "receiving a boolean", make sure to debug the value before running any statements. I'm sure it's still a string when going into the function.
Related
I have added confirmation dialog to input again the status I get before submitting.
That park works.
Problem is that prompt() function does not except inputing just numbers?
Is there anyway I can added that part to so it can pass?
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});
Any idea how to fix the code? I am pretty new at jQuery and JS. Thanks
I want to cover both cases. With string and with number.
jQuery's .data() method automatically parses the data as JSON if it can, so if it looks numeric it will return a number, not a string.
prompt() always returns a string (or null if you cancel).
So you need to convert status and statusInput to the same type if you want to compare them with ===. You can use parseInt() to convert the user input to an integer.
$(".delete-status").click(function(ev, el) {
var status = $(this).data("status");
var statusInput = parseInt(prompt("Confirm deletion by entering the status:"));
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});
You could convert statusInput string to a number.
This could be better but something along the lines of:
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (Number(statusInput) === Number(status)) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
})
I have this small javascript to validate form input.
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
I'm tryin to figure out how to get the "alert" message as a string to show it later on the page instead of popping this ridiculous box. Looks simple to me but i'm a big zero in js. Any help appreciated, Thanks !
The alert() method is what makes the big pop up box. If you want to save the value for later use save it to a variable. Something like:
var message = "";
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
message = "Some fields need correction:\n" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
var alerter;
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alerter = "Some fields need correction:<br/>" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
document.body.innerHTML = alerter;
How about assigning the string to a property of "window" :
window.myAlert ="Some fields need correction:\n" + reason);
Then you can get it from anywhere:
document.body.innerHTML = window.myAlert;
I need some guidance, as im literally going crazy here.
Ive created code with php/js/ajax to check if email address exist when submitting.
So ive tested the ajax and the correct values are being returned. (checked via firebug)
Either 1 for user exists
or 2 for user doe not exist.
Now ive added an alert box to check the value and for some strange reason it always displays value 1!
(even though ajax value is 2)
function validateForm() {
var x3=document.forms["newuser"]["email"].value;
//Check if username exists.
$.post(
"http://...check_user_exists.php",
{
x3 : x3 //user email
},
function(data) {
email_check = parseInt((data.email_exists),10);
}
);
//Additional Checks
if (email_check = 1) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
alert(email_check);
return false;
}
if (email_check = 2) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
alert(email_check);
return true;
}
more validation checks....
Hi all, and again... thank you for your kind guidance.
Firstly, I would like to apologize as i'm quite new to this...
I've moved forward slightly but stuck on the last part and not sure how to proceed.
So the form now validates the form elements and checks the email to see if it exists.
The only issue I have left is if the email value is ok, the form does not process.
Is there a way to set submit value to true with the ajax callback function?
<form name="newuser" id="form" method="post" action="do_new_user.php" onsubmit="return validateForm()">
function validateForm()
{
var x=document.forms["newuser"]["name"].value;
var x2=document.forms["newuser"]["surname"].value;
var x3=document.forms["newuser"]["email"].value;
var x4=document.forms["newuser"]["password1"].value;
var x5=document.forms["newuser"]["password2"].value;
if (x==null || x=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please enter your name.");
return false;
}
//more validation.....
//Check if username exists.
$.post("http://ryangosden.com/breadcrumbs/check_user_exists.php",
{
x3 : x3
} ,
function(data)
{
var obj = jQuery.parseJSON(data);
if (obj.email_exists == 1)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
}
if (obj.email_exists == 2)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
validateForm(true);
}
});
return false;
}
Thanks again all.
You are not comparing but assigning 1 to email_check
if (email_check = 1)
but should be
if (email_check == 1)
= is an assignment operator
== is a comparison operator
=== is a strict comparison operator
why you are assigning the value instead of comparing it.
= assigns the value
== compares the value
if (email_check = 1)
you should do this:
if (email_check == 1)
and
if (email_check == 2)
The callback function is called asynchronously. Therefore you cannot call validateForm() in the way that you are expecting to, which contacts the server, parses the result, and returns true or false. What actually happens is that the $post( ... code runs, but does not wait for the response. Instead, it immediately continues through the code if (email_check = 1) { ... (which should have a == instead of =) without waiting for the POST response. Only later when the response is received is email_check actually set via the callback function, but the remainder of validateForm() has already completed.
Instead, whatever you intend to do with the return value, you must do in the callback function itself. That is, replace
function(data)
{
email_check = parseInt((data.email_exists),10);
});
with
function(data)
{
email_check = parseInt((data.email_exists),10);
alert("In callback: email_check = "+email_check);
if (email_check == 1) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
}
if (email_check == 2) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
}
});
Anything else you were doing with the return value of validateForm() should also go in the callback function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
So this is my code for some ajax that I'm doing.
function check_password(){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
},
function(response) {
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
return response.indexOf('success');
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
and here I'm trying to handle the return value from the check password function.
jQuery(function() {
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
} else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
} else if (check_password() != 73) {
hasError = true;
$("#password").after(check_password());
}
if (hasError == true) {
return false;
}
});
});
For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.
Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.
To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.
Your function ´checkpassword()´ doesn't actually return a value.
It launches a request to a PHP-file and immediately returns (without a value).
You do specify a callback for when the call returns, but that never gets back to your original function.
You could do something like this:
function check_password(callback){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
callback(response.indexOf('success'));
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
jQuery(function(){
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
}
else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
}
else (
check_password(function(returnValue) {
if (returnValue != 73) {
hasError = true;
$("#password").after(check_password());
}
})){
}
if(hasError == true) {return false;}
});
});
Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.
Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:
function check_password(callback) {
// ...
callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
if(result != 73) {
// ...
}
})
Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/
I have this function
$.fn.validate.checkValidationName = function(id) {
$.post("PHP/submitButtonName.php", {checkValidation: id},
function(data) {
if(data.returnValue === true) {
name = true;
} else {
name = false;
}
**console.log("name = "+name); **//this prints out "true"****
}, "json");
};
and this .click function that calls it. All the variables are declared outside this function so that they should be accessible by other functions
$('.submitBtn').click(function() {
//clears the array before re-submitting the click function
nameValues = [];
usernameValues = [];
emailValues = [];
name = false;
username = false;
email = false;
//for each of the input tags
$("input").each(function() {
//if the curent input tag has the class .name, .userpass, or .email
if(($(this).hasClass("name"))) {
nameValues.push($(this).val());
} else if(($(this).hasClass("userpass"))) {
usernameValues.push($(this).val());
} else if(($(this).hasClass("email"))) {
emailValues.push($(this).val());
}
});
//call the checkValidation function with the array "values"
$.fn.validate.checkValidationName(nameValues);
$.fn.validate.checkValidationUsername(usernameValues);
$.fn.validate.checkValidationEmail(emailValues);
console.log("name = "+name); //but this prints out "false"
console.log("username = "+username);
console.log("email = "+email);
if((name === "true") && (username === "true") && (email === "true")) {
alert("Everything checks out great");
} else {
alert("You missed one!");
}
});
When I click the link to trigger the first function, it returns the value as "true" inside the function, but when I console.log("name"+name); in the .click function after the function call, it prints out false.
Why is this? Do I need to return something from the checkValidatoinName function?
$.post is asynchronous, which means that it won't wait for the result to get back before proceeding. You're probably initializing name to true somewhere, and it's getting true the first time, but all the other times, it's false, because the AJAX from the first one finished and set it to false.
Try using $.ajax instead of $.post, and set async to false in the options. The $.post documentation shows the options that $.post would give to $.ajax.