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

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.

Related

jquery ajax onsubmit form error

I hava a form that is given below
<form name="frm_dcg" id="frm_dcg" method="post" enctype="multipart/form-data" action="" onsubmit="return validate_form();" >
<div class="login-form">
<div class="sign-in-htm">
-----------other codes-------
and the jquery function
function validate_form(){
var run_name = $("#run_name").val();
$.ajax({
url: "check_folder.php",
type: "POST",
data: "run_name="+run_name,
success: function (response) {
if(response=="OK"){
con = confirm("File already exists.. Do you want to replace existing file?");
if(con==true){
return true;
}else{
return false;
}
} else{
return true;
}
return false;
}
});
}
The ajax is working fine, but the problem is form is submitting in any conditions. even if it is returning false. Please go through my code and let me know if there is any logical mistakes.
Ajax is an asynchronous function, meaning the return false you are calling happens way after the form is submitted.
Instead you have to add the return false at the end of the validate_form() function.
function validate_form(){
var run_name = $("#run_name").val();
...
return false; // <-- before the ending curly brace
}
Note that the form should always return false. You can validate run_name use that to decide if you should do the ajax request or not.
function validate_form(){
var run_name = $("#run_name").val();
if (run_name.length > 5) { // just an example
// do ajax request
} else {
// show invalid message
}
return false; // always false so the form doesn't submit.
}
You're returning the true/false result within the success closure. This won't get passed up to validate_form(). You also have a logic bug in the success handler that always returns true even if the response wasn't 'OK'.
You'll need to do something like:
function validate_form(){
var form_success = false; // Always fail by default
var run_name = $("#run_name").val();
$.ajax({
url: "check_folder.php",
type: "POST",
data: "run_name="+run_name,
success: function (response) {
if (response == "OK"){
form_success = confirm("File already exists.. Do you want to replace existing file?");
}
form_success = false;
}
});
return form_success;
}

submit form with ajax validation jquery / standard javascript

I'll start with an apology - I'm a .NET coder with little (no) front-end experience.
When the user clicks on Submit, the form needs to call a REST service, if the service returns true then the user is presented with a warning that a duplicate exists and are asked whether they want to continue. Appreciate any help.
I have the Submit button ONCLICK wired up to Approve()
When the checkForDuplicateInvoice() gets called, it passes the control back to the calling function right away before the ajax call has a chance to get the result. The effect is that the Validate() function finishes without taking into account whether or not a duplicate invoice exists.
I need help in modifying the form so that when the user clicks on the submit button, the form validates (including the ajax call to the db) before finally submitting.
I've modified the code based on Jasen's feedback.
I'm including https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js in my header.
The error I get now is "Object doesn't support property or method 'button'"
What I have now for my form submission/validation is:
$(document).ready(function () {
$("#process").button().click( function () {
if (ValidateFields()) { // internal validation
var companyCode = document.getElementById("_1_1_21_1").value;
var invoiceNo = document.getElementById("_1_1_25_1").value;
var vendorNo = document.getElementById("_1_1_24_1").value;
if (vendorNo == "undefined" || invoiceNo == "undefined" || companyCode == "undefined") {
return false;
}
$.ajax({ // external validation
type: "GET",
contentType: "application/json;charset=utf-8",
//context: $form,
async: false,
dataType: "jsonp",
crossDomain: true,
cache: true,
url: "http://cdmstage.domain.com/services/rest/restservice.svc/CheckDuplicateInvoice?InvoiceNumber=" + invoiceNo + "&VendorNumber=" + vendorNo + "&CompanyCode=" + companyCode,
success: function (data) {
var result = data;
var exists = result.CheckForInvoiceDuplicateResult.InvoiceExists;
var valid = false;
if (exists) {
if (confirm('Duplicate Invoice Found! Click OK to override or Cancel to return to the form.')) {
valid = true;
}
}
else {
valid = true; // no duplicate found - form is valid
}
if (valid) {
document.getElementById("_1_1_20_1").value = "Approve";
doFormSubmit(document.myForm);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
});
});
First review How do I return the response from an asynchronous call? Understand why you can't return a value from the ajax callback functions.
Next, disassociate the submit button from the form to prevent it from performing default submission. Test it to see it does nothing.
<form>
...
<button type="button" id="process" />
</form>
Then wire it up to make your validation request
$("#process").on("click", function() {
if (valid()) {
$(this).prop("disabled", true); // disable the button to prevent extra user clicks
// make ajax server-side validation request
}
});
Then you can make your AJAX request truly asynchronous.
$.ajax({
async: true,
...,
success: function(result) {
if (exists) {
// return true; // returning a value is futile
// make ajax AddInvoice call
}
}
});
Pseudo-code for this process
if (client-side is valid) {
server-side validation: {
on response: if (server-side is valid) {
AddInvoice: {
on response: if (successful) {
form.submit()
}
}
}
}
}
In the callback for the server-side validation you make the AddInvoice request.
In the callback for AddInvoice you call your form.submit().
In this way you nest ajax calls and wait for each response. If any fail, make the appropriate UI prompt and re-enable the button. Otherwise, you don't automatically submit the form until both ajax calls succeed and you call submit() programmatically.

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.

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