Here is a little problem that I cannot figure out…again…
I have a sign up form with onsubmit attached to a js function
This js function calls .ajax to verify the users inputs and outputs the error messages above the input boxes.
I desperate need this function to tell me if error exists or not by returning a true of false value, but since (i am guessing) ajax is asynchronous, the function always returns false before calling ajax:
function submit_signup(){
var result = true;
ajax code (if error then result = false)
return result;
}
You will need the onsubmit handler to prevent the default action, so that only when the ajax response comes back and the response is true, you can then submit it from there.
var form = document.querySelector('.signup').onsubmit = function (evt) {
evt.preventDefault();
// ajax_stuff_here
};
I’m not sure if the this keyword is referring to what you think it is either. When dealing with nested levels and changing scopes, it can get confusing as to what this refers to. A good way to prevent confusion is to cache a reference to the form:
$('#signupForm').submit(function(event){
var form = this;
...
});
Now you can submit the form and guarantee that you are calling the right thing, with:
Being a perfectionist, I am a bit annoyed by how un-minimalistic my design is.
What I am doing is:
When user clicks the submit button
→ Disable the default action
→ Call ajax to run check_signup.php to check each user input and print error messages
→ if everything goes well, submit the form using javascript
→ form submits to signup.php
→ signup.php writes to database, and then send out activation email by posting toactivation.php
What I don’t like is
due to security reasons, I have to put the input validation code twice, once in check_signup.php and then again in signup.php.
the user won’t be able to read error messages if javascript is disabled
if somehow an user actually runs the check_signup.php they will see a lot of database structure.
[quote=“johnhuichen, post:6, topic:198306”]
What I don’t like is1) due to security reasons, I have to put the input validation code twice, once in check_signup.php and then again in signup.php.[/quote]
This is where it’s handy to have the validation code in a separate file, so that you can then include it where and when required in other files.
A standard process to use here is to get things working first without JavaScript, and to then use JavaScript to improve the user experience.
Moving the success validation to the PHP code, so that only an output of true or false is given, will help to deal with that level of security.