Return from jquery to javascript? - javascript

So I'm pretty new to Javascript and even newer to jQuery. Working on this project atm, I started with Javascript but a lot of the solution to my issues were a lot easier in jQuery.
so I have some javascript which basically prevents the user from pressing submit if all the forms have not passed validation.
So this is my field.
<td><input type="password" maxlength="16" name="passwd" id="passwd" onblur="validatePassword(this.value)" /></td>
<td><span id="pMess"></span></td>
This is my submit.
<td><input type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
As you can see when you press submit it goes to the validate function which is:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
if ( valid ) return true;
else return false;
}
And finally this is the field checker.
function validatePassword(passwordString) {
var valid = true;
if ( passwordString == "" ) {
feedback('pMess','Enter your password here');
valid = false;
} else if ( passwordString.length <= 5 ){
feedback('pMess','Password too short');
valid = false;
} else feedback('pMess','Acceptable');
if ( valid ) return true;
else return false;
}
My username field checker is slighty different as it's in jQuery
$(document).ready(function() {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
so what I'm trying to do is get username_check to return like my other field checkers. I'm just looking for help as to where I should put the returns and stuff. Whatever I try seems to break the code...
All I have so far
if ( !check_username(theForm.username.value) ) valid = false;
Any help at pointing me in the right direction would be much appreciated.

The problem is not jQuery. The problem is that you are using an asynchronous call to do some of your validation. jQuery.ajax is asynchronous, meaning that code will continue to execute while it fetches check.php. In other words, by the time the response comes back, username_check() will have already returned and submitted your form (or cancelled the submit).
For the non-AJAX part of your code (the length check), you can do a return just fine:
function username_check() {
var username = $('#username').val();
// NOTE: This is redundant, as "" has length 0
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
return false; // This will work here
} else {
// AJAX stuff
}
}
Unfortunately, the rest gets a bit more tricky. What you really want to do, is wait to sumbit your form until the username check is done, which means your submit needs to go in the callback function (i.e. the success part of your AJAX). If you only have one AJAX call, this is not too bad. If you have multiple AJAX calls, you need to either nest all of the calls (which makes the code take longer, is not very pretty, and will not easily proceed to other checks after one fails) or you need to use deferred objects (or something similar), which are not trivial (but very useful).
Assuming you have a single AJAX call for username:
First, add an ID to your submit button. This makes it easier to reference from jQuery:
<td><input id="mysubmit" type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
Secondly, do the username check after all of the other checks, and only submit if the other checks were valid:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
// The non-AJAX checks for username length:
var username = theForm.username.value;
if ( !validateUsername(username) ) valid = false;
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
// If the other checks were OK, submit the form manually
if(valid) {
$("#mysubmit").submit();
}
}
}
});
// ALWAYS return false.
// We will submit the form manually if the checks are OK
// For now, prevent the submit
return false;
}
Make sense?
Notes:
You probably want to disable the submit button after it is clicked (and re-enable it on failure. Otherwise, if the AJAX takes a while, a user could potentially change the field values before its callback, allowing bad data to be submitted without checks.
The other solution to this is to do the checks onsubmit. Currently, your checks are not called if the user pressed the enter key. This is bad!

Not sure if I follow, you want the function to return true or false if validates, right?
Edit: my code was crap, thanks roasted for pointing that out.
So, as you are doing an ajax call you can't really get if it's valid (true or false) in the same function, you probably need to do something different....
A couple of ideas;
-Use your DOM (add an "invalid" class or something like that to the form field and then check for that value.
-Use a global variable "valid_user" saving the result of the validation... ( i know global variables suck and it's a bad practice, but hey, if you have a deadline...)
then, when you are validating the hole form, check for this things instead of calling username_check again.
Hope this helps!

Related

Client-side validation is not posting values

I have a form that validates a value at a time. When all the values are validated and correct my ajax post function does not want to post. I would like to post when all the values are correct. One text field has a name, the last text field is an email.
Please check my jsFiddle and the code below.
HTML:
<form enctype="multipart/form-data" method="post" id="myform" name="myform_1">
<input type="text" value="" id="name" name="myname" />
<input type="text" value="" id="email" name="myemail"/>
<input type="submit" value="Valid" id="validate" name="validate"/>
</form>
Javascript:
$(document).ready(function(){
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}
//Click action
$("#validate").click(function()
{
var name = $( "#name" );
var email = $("#email");
var valid = true;
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
valid = valid && checkLength( name,"Please enter a name",3,6);
valid = valid && checkRegexp( name, /^[a-z]([A-Z_\s])+$/i, "Name may consist of a-z, and 3 or more characters." );
valid = valid && checkLength( email, "email", 6, 80 );
valid = valid && checkkRegexp( email, emailRegex, "eg. ui#jquery.com" );
//Email
//alert ($("#myform").serialize());
//End of Email
if(valid)
{
var request = $.ajax({
url: "inc/newsletter.php", // Ofcourse this would be your addLike.php in your real script
type: "POST",
data: $("#myform").serialize()
});
request.done(function(msg) {
alert("Your details have been saved");
location.reload();
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
return valid;
}
else
{
alert("No;")
}
});
});
Your submit event handler is not returning false, hence it is posting the form completely. First, make sure the event bubbling is stopped in the click handler
in the following manner:
$("#validate").click(function(event)
{
//YOUR AJAX CALL
//RETURN SHOULD ALWAYS BE FALSE FOR AJAX SUBMISSION WHEN CALLED FROM TYPE BUTTON
event.preventDefault();
event.stopPropagation();
return false;
})
You can then trace if the ajax call happens in the browser console...
Hope it helps!
Friend, youre calling this function "checkkRegexp" that doesnt exist!!
And you should return false at the end of youre function to prevent the form submission if some validation goes wrong!
You should also have a look at "parsley". This will help you with form validations.
Change the start of your function like this
$("#validate").click(function(e){
e.preventDefault();
//Rest of your function
}
e.preventDefault() is not cross browser compatible and might break in older browsers. Use the following if you support older browsers
if(e.preventDefault()!=undefined){
e.preventDefault();
}else{
e.returnValue = false;
}
If you are interested in knowing why your approach is not working. The button you are clicking is a submit button and you are not preventing it default behavior. This is the reason that form is submitted even though your form fields are incomplete.
Point to note is still ajax cal won't be called in example provide but it will be natural form refresh.
Solution provided will stop default action and will give full control to your ajax request and validations

Prevent form submission in jQuery by ID

I am using jQuery Ajax function to check the existence of user email in the database on jquery change function. in Ajax responsive there are two possibilities that either user email exists or not. If it exists it shows the error message. Now I wanted to prevent the form from submitting if the Ajax responsive is false
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
//prevent form here
}
else {
// else condition goes here
}
});
You can put a global variable like
emailValidated = false
And on
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
emailValidated = false;
}
else {
// else condition goes here
emailValidated = true;
}
});
After that on form submit check the value of the emailValidated variable.
$(form).submit(function(){
if(emailValidated) {
this.submit();
}
else {
return false;
}
})
Use e.preventDefault() to prevent form from submission.
jQuery("#userEmail").change(function(e){
if(result == 'False'){
e.preventDefault();
}
else {
}
});
Do something like this:
var result;
$.ajax({
url: url,
// Put all the other configuration here
success: function(data){
if(data == something) // replace something with the server response
result = true; // Means that the user cannot submit the form
},
});
$('#formID').submit(function(){
if(result){
alert('Email already exists.');
return false;
}
});
Steps are like :
get the email value passed by the user from input field in Jquery.
The POST that data to your PHP query file and get the response data on "success: function(data)" function of jquery.
Display that data data on the page..
Check below link for a reference.
http://www.sitepoint.com/jquery-ajax-validation-remote-rule/
You need use the submit event handler:
jQuery("#userEmail").closest("form").submit(function(event){
var $email = jQuery("#userEmail", this);
//the email field is not `this`, but `$email` now.
//your code goes here
if(result == 'False'){
event.preventDefault();
}
else {
// else condition goes here
}
});
You can still attach other behaviours to the change event if needed. The important thing is to do event.preventDefault() on the submit event.

Check if username already exists - only working with onclick

I'm trying to check if username and email already exist on a register page.
I've got this javascript code:
var nombre = document.getElementById("username").value;
var email = document.getElementById("email").value;
var errorNombre = document.getElementById("erno");
var errorEmail = document.getElementById("erem");
if (nombre == null || nombre.length == 0 || /^\s+$/.test(nombre)) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Debe introducir un nombre de usuario</font>";
return false;
} else {
$.ajax({
type: 'POST',
data: {
email: email
},
url: 'consulta5.php',
success: function (response) {
if (response != 0) {
errorEmail.innerHTML = "<font color='red' face='century gothic'>Correo ya registrado</font>";
return false;
} else if (response == 0) {
//desde aquí
errorEmail.innerHTML = "";
$.ajax({
type: 'POST',
data: {
nombre: nombre
},
url: 'consulta4.php',
success: function (response) {
if (response != 0) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Nombre de usuario no disponible</font>";
return false;
}
}
});
}
}
});
}
And it works perfectly if it's part of a $( "#enviar" ).live("click", function(){, but tha problem is that this way the form is not sended if everything's ok. However, if I try to use the on submit = "return validate ()" only the first part of the javascript works, and the form is sended whenever the mail exists or not (but not when there are some blank spaces).
I'd really appreciate some help, because I don't have any idea on how to make this work!!
thanks :)
The form is not submitted because you never tell it to be. If, however, you change your innermost success function to something like:
success: function (response) {
if (response != 0) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Nombre de usuario no disponible</font>";
return false;
}
else {
$("#yourForm").submit();
}
}
then I believe your logic will be sound.
That said, there are some other changes I would recommend.
First, consider reworking your validation php to check both fields (name and email) in a single call. You can use a single response value to indicate which (if any) failed. If you want numeric response codes, then you could do something as simple as 0 for all's well, 1 for bad email, 2 for bad name, 3 for errors in both. There's really no need to be making two sequential trips to validate data that has no interdependencies.
Second, consider using CSS! There's no need to be using <font> here. Put a style (if you must) or a class (preferable) on errorNombre and errorEmail. If there are multiple errors that might be shown in those places, then just set the error text dynamically. If these are the only errors that go there, you don't even need that - put the error message in your HTML, and just dynamically show or hide the element.

How do I submit a form using jQuery after AJAX validation?

My form has one input which needs to be validated before submitting. After a successful validation I try to submit the form, but it doesn't submit.
My code looks like this:
$(document).ready(function() {
$("#myForm").submit(function () {
checkInputData();
return false; // to prevent default submit
});
});
The validation function:
function checkInputData() {
var id = $($("#id")).val(); // value, which needs to be validated
$.get("check.php?id=" + id,
function(result){
if(result == 1) {
//if the result is 1, need to submit
$("#myForm").unbind(); // to prevent recursion?
$("#myForm").submit(); // doesnt work
} else {
// dont submit, give some visual feedback, etc...
}
});
}
What am i doing wrong? Thanks.
You need to return the result from your AJAX validation request. You can do this by setting this check to being async: false, this means the checkInputData() will wait for the result to come back, and you can return it, controlling the submission of the form.
In your code it's not waiting for the $.get action to happen, and it appears to skip over meaning your code will always appear to return true; from the checkInputData() call. You don't need to return false in submit, if used as below.
I have used the $.ajax call in place of $.get because it allows you to control the async property, but it essentially does the same thing. You can read more about it here.
function checkInputData() {
var value = $("#id").val(); // Value to be validated
var passedValidation = false;
$.ajax("check.php?id=" + value, {
async: false,
success: function(result){
// Do whatever check of the server data you need here.
if(result == "1") {
// Good result, allow the submission
passedValidation = true;
} else {
// Show an error message
}
}
});
return passedValidation;
}
$(document).ready(function() {
$("#myForm").on("submit", function () {
return checkInputData();
});
});
I assume you have a button such as below, within your form with id myForm:
<input type="submit" value="Submit Form" />
It's not getting submitted may be because you are not returning 1 on successful validation for result in below if condition
if(result == 1) {
In check.php your output should be 1, like echo '1'; if input is valid. And make sure there is not any other output before or after it.
AMember is correct your always returning false, there are a few solution. One solution is for you to bind your validation to a button element or any element that will not submit the form.
HTML
<form id="myForm">
.
input elements
.
<button class= "submit" type="button" onclick="submit">Submit</button>
</form>
Document Ready
$(function()
{
var $submit = $(".submit");
$submit.click(function ()
{
checkInputData();
});
});
Validation Callback Function
function checkInputData()
{
var id = $('#id').val(); // value, which needs to be validated
$.get("check.php?id=" + id, function(result)
{
if(result == 1)
{
var $myForm = $("#myForm");
//if the result is 1 submit.
$myForm.submit();
}
else
{
// dont submit, give some visual feedback, etc...
}
});
}
$(document).ready(function() {
$("#myForm").submit(function (e) {
checkInputData();
//return false; // to prevent default submit <-- THIS IS WRONG
e.preventDefault(); //Try this :)
});
});
Returning false will prevent it from submitting in all cases.

$posts jquery submits my form

<script type="text/javascript">
function claim()
{
var c = confirm('You sure?');
if(c)
{
var password=prompt("Please mention pw","");
if (password!=null && password!="")
{
$.post("/claim/<?php echo $refnr; ?>", { partner_pwd: password },
function(data) {
alert(data);
if(data == '1')
{
return true;
}else{
return false;
}
});
}else{
return false;
}
}else{
return false;
}
}
</script>
When testing I get to the Please mention pw, after i entered and press OK it submits my form, instead of making the $.post and only submit my form if data == '1' (return true)
claim() is called at my submit button;
<input type="submit" name="submit" onclick="return claim()"; value="Submit" />
I tried alert debugging and it was true like i thought it automatically submits when it reads the $.post(), I only wish it to submit (by returning true) if the data is 1.
Well, if you put a form in a website, it's goal is to submit the form.
http://api.jquery.com/submit/ (scroll down to the very last example starting with Example: If you'd like to prevent forms from being submitted unless a flag variable is set, try:)
As stated in the link above, you should change form's action instead of some page and do something like action="javascript:claim()". I think that should work.
The return true and return false inside of your $.post request do nothing but return out of that callback. It does not prevent the form from submitting. Instead, try preventing the submit completely and then triggering it if you want the submit to happen.
function claim() {
var c = confirm('You sure?');
if (!c) {
return false;
}
var password = prompt("Please mention pw", "");
if (password != null && password != "") {
$.post("/claim/<?php echo $refnr; ?>", {
partner_pwd: password
}, function(data) {
alert(data);
if (data == '1') {
$("#myform").submit();
}
});
}
return false;
}​
Note how we always return false out of that function regardless of the validity. If it is valid, we trigger the form's submit event directly.
Your onclick method on the submit it's not working because the form will be submitted eitherway.
You should for example set a listener on the onsubmit(); event on the form
or another solution is on the put the onsubmit attribute with your javascript function in it and submit the form from your javascript with the $('#form').submit(); function.

Categories

Resources