Client-side validation is not posting values - javascript

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

Related

Post a form using Jquery ajax and get the response

I'm using this code to post a form using jquery ajax .
my problem is that i want to make php code to be like this:
if (isset($_POST[''])) {
// some code here
}
this is the javascript code:
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" )
$("div#status").html("Please enter your Email");
else
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
If you tested the code, and the php section works fine, but you can not get a response in jquery, then, you should check your php code(It should be like this):
if (isset($_POST[''])) {
$data = "";
// some code here to fill $data
echo $data; // this is the actual response to the jquery interface.
}
There are 6 b's in php file name but 7 b's in ajax url.
url: "bbbbbbb.php", <--- 7 b's
bbbbbb.php <--- 6 b's
Plus, along with success you should have error also so you'd see what the error is.
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
Despite a lack of actual question, here's a crack at an answer.
The first issue is that the javascript, while working, won't get to do the complete job it's supposed to do. The javascript code appears to want to prevent the form from being manually submitted via the submit event. You may want to reorganise the javascript to look like:
$("#myForm").submit( function() {
return false;
});
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" ) {
$("div#status").html("Please enter your Email");
} else {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
}
});
Additionally, you may want to look up usage of modern event watching in jquery, and the usage of .on(). i.e. $("#myForm").on("submit", function() {});. But that's not quite the point of this post.
As for the PHP code, let's infer you have the following HTML form:
<form action="login.php" id="myForm">
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
<button type="submit" id="submit" name="submit" value="submit">Submit</button>
</form>
<div id="status">Please provide username and password to login</div>
In login.php, you would have
if (!empty($_POST)) {
if (isset($_POST['submit']) && $_POST['submit'] == 'submit') {
// validate $_POST contains username and password
...
// sanitize username and password
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);
// do my processing
// doLogin returns true for successful login, or message contain error string
$result = doLogin($_POST['username'], $_POST['password']);
if ($result === true) {
echo 'You have successfully logged in';
} else {
echo $result;
}
} else {
echo 'Unknown form action';
}
} else {
// do GET processing
}
With this, just echo the response you want to appear in the div#status.

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.

remember password after jquery post

Here is code
<script type='text/javascript'>
$("#focusform").submit(function(event)
{
event.preventDefault();
var $form = $( this ),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
if($('#chk').is(':checked')) var checked='yes';
else var checked='no';
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("You have made an error");
return false;
}
else{
if(checked=='yes')window.location='/usercookie/';
else window.location='/login/success/';
return true;
}
});
});
</script>
But browser doesn't want to promt whether save password or not. Cant't you help me?
I would do a pre check and use Ajax to check the is correct, this would then return the error or success message, if success continue to post the form otherwise display the error using Ajax
The browser won't offer to save passwords if your <form> doesn't have an action URL and doesn't have a submit button. Your password field must also be an <input type="password" />.
It doesn't work when you try to assign the submit function with jQuery in that way:
$("#focusform").submit( ...
However it does work if you add an onsubmit attribute to the form:
<form id="focusForm" action="page.php" method="post" onsubmit="return mySubmit()">
^^ here
And then return false in your submit function:
function mySubmit()
{
// do the jquery ajax or whatever you want to do here
return false;
}
<iframe id="temp" name="temp" src='/engine/blank.html' style="display:none"></iframe>
<form id='focusform' target='temp' method='post' onsubmit="return mySubmit()">
...
</form>
<script type='text/javascript'>
function mySubmit()
{
var $form = $("#focusform"),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
var checked = ($('#chk').is(':checked')?'yes':'no');
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("<?=$lang['made_error']?>");
}
else{
alert("Loged in");
}
});
}
</script>
And it works :)

Return from jquery to 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!

$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