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.
Related
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.
So I have this Javascript code:
function AddToStuff(somethingID) {
var stuffID = document.getElementById('StuffID').innerText;
alert("First Alert: " + stuffID);
if (stuffID == -1) {
document.getElementById('StuffID').innerText = 0;
stuffID = 0;
}
alert("Second Alert: " + stuffID)
StuffCallback.fire(somethingID, stuffID);
}
$(document).ready(function () {
initializeStuff();
});
var StuffCallback = $.Callbacks();
function initializeStuff() {
StuffCallback.add(function (somethingID, stuffID) {
$.ajax({
url: "pos/Stuff",
type: "GET",
traditional: true,
data: {
somethingID: somethingID,
stuffID: stuffID
},
success: function (result, textStatus, xhr) {
alert("Third Alert: " + stuffID);
var contentArea = $("#Stuff");
contentArea.html(result);
$("#Stuff").hide();
$("#Stuff").show({ duration: 250 });
}
});
});
}
And this C# code:
public ActionResult Stuff(int somethingID = 0, int stuffID = -1)
{
if (stuffID == -1)
{
//do something
}
else if (stuffID == 0)
{
//do something else
}
else
{
//do something else
}
}
return View();
}
}
The problem is that the C# method always has stuffID at -1 and so performs the first "if" case.
When the page loads and $(document).ready calls initializeStuff, the stuffID is -1, so it performs the first "if" case, as desired. Later, when AddToStuff() is called, because the user clicked on something, it reads in my element StuffID, which I have initialized to -1. The First Alert does display the -1. Then StuffID gets changed to 0 in the "if" inside AddToStuff() and the Second Alert does display the 0.
But then I have the Javascript function AddToStuff call the C# function again, but the goal is to have the second parameter (stuffID) be the 0 instead of the -1. And even the Third Alert will display a 0. But in the C# function, the stuffID is still -1.
I can't pass in the 0. Any help would be appreciated.
Note: I generalized my code into "something" and "stuff", but that part should be working fine - the functions call when I expect them to.
Suggestions:
Use fiddler or developer tools in your browser to see what is being passed to the server (0, or -1)?
The default value to Stuff(int somethingID = 0, int stuffID = -1) can also be causing the problem if the data received by the server is not correct.
Set the data type in your Ajax call dataType: 'json'
If you are using a GET request, make sure that you have set the data object correctly
If I comment all your JS code and just write
StuffCallback.fire(0, 5);
it works nicely, as it accepts 5. That means that your stuffID is not being recognized as int. What kind of a HTML element is it? I see you are using .innerText. As you are using jQuery already, why not use
var stuffID = $('#StuffID').val();
I have noticed your problem though. You have a typo.
getElementById('StuffID') and your p is called "stuffID". JS IS case sensitive, so it will be enough to fix that, but please use
<input type="hidden" ID="StuffID" value="#stuffID">
as that's proper HTML markup
I have a JSP with the form "deleteCont" and a javascript file with the function "validateDelete". When I click the "Delete contact" button the "validateDelete" function is successfully called and the alert with the "alertmessage" is displayed. However, the "ContactMaint" servlet is still called even though false is being returned. Please can someone tell me where I am going wrong?
<form name="deleteCont"
onsubmit="return validateDelete('${sessionScope.account}','${sessionScope.firstname}', '${sessionScope.lastname}')"
action="ContactMaint" method="post">
<input type="submit" value="Delete contact" name="delContact">
</form>
function validateDelete(account, contactFirstName, contactLastName) {
urlstrg = "http://localhost:8080/SalesPoliticalMapping/JCheckContacts?account=" +
account + "&firstname=" + contactFirstName + "&lastname=" + contactLastName;
$.get(urlstrg, function (result, status) {
if (result.length > 0) {
var alertmessage = "Can't delect contact:";
for (var i = 0; i < result.length; i++) {
alertmessage += result[i];
}
alert(alertmessage);
return false;
}
});
}
I have now amended my code as follows although I'm not entirely sure why:
function validateDelete(account, contactFirstName, contactLastName) {
$.ajaxSetup({async: false});
urlstrg = "http://localhost:8080/SalesPoliticalMapping/JCheckContacts?account=" + account + "&firstname=" + contactFirstName + "&lastname=" + contactLastName;
var valid = true;
var alertmessage = "";
$.get(urlstrg, function(result, status) {
if (result.length > 0) {
valid = false;
alertmessage = "Can't delect contact:";
for (var i = 0; i < result.length; i++) {
alertmessage += result[i];
}
}
});
if (valid===false) {
alert(alertmessage);
return false;}
};
There are 2 problems:
You're firing an ajax request. Ajax requests are by default asynchronous. Immediately after the $.get() called, the code advances to the next line while the asynchronous request runs in the background in a completely different thread. As there's in your case apparently nothing after the $.get(), it immediately returns (implicitly as true).
You're returning from a callback function, not from the main function. The callback function only returns into the main function, not outside. You need to return from the main function.
One way is to always return false and explicitly submit the form on success.
function validateDelete(...) {
var $form = $(this);
$.get(..., function(...) {
if (success) {
$form.submit();
}
});
return false;
}
Another way is making the ajax request asynchronous by passing { async: false } option as 2nd argument of $.get().
function validateDelete(...) {
var valid = false;
$.get(..., { async: true }, function(...) {
if (success) {
valid = true;
}
});
return valid;
}
Please note that this problem has completely nothing to do with JSP. You'd still have had exactly the same problem when using the same script in another view technology, such as PHP, ASP, etc, and even in a plain HTML page. JSP is in the context of this question merely a HTML code generator and can better be omitted from the question in future problems with specifically HTML+CSS+JS/jQuery.
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.