jquery ajax onsubmit form error - javascript

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;
}

Related

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.

Submit form after event.preventDefault?

I know this question has been asked a million times but i just cant seem to make it work. Can someone let me know what I'm doing wrong.
Here's my code:
$('#frm').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
var email = $('input#email').val();
if (email == '') {
alert('Please enter your email address');
$('input#email').focus();
return false;
} else {
$.post('http://www.domain.com/', formData, function() {
$('#frm').submit();
});
}
});
You can submit the FORM using DOM node submit method:
$.post('http://www.domain.com/', formData, function() {
this.submit(); // 'this' not '$(this)'
}.bind(this)); // 'bind' to set relevant context, or use jq $.proxy(handler, this) to support older browsers
This code does not make sense
$.post('http://www.domain.com/', formData, function() {
$(this).submit();
});
you are posting and then, when the request returns with success, you are trying to call submit on the form again?
by the way, this in that context refers to the jqXHR object of the Ajax call and not to the form. See $(this) inside of AJAX success not working
As most of the answers said, this is not a reference to the form. Then you will need to create a reference for it as follows (see that var). HOwever that is only needed if you want to use it later in the success callback:
$('#frm').submit(function(event) {
// Create a reference to your form
var that = this;
event.preventDefault();
var formData = $(this).serialize();
var email = $('input#email').val();
if (email == '') {
alert('Please enter your email address');
$('input#email').focus();
return false;
} else {
$.post('http://www.domain.com/', formData, function() {
// On success response do your stuff here and
// submit to your 'own domain'
// In case you don't have the action attr, give a value to this var.
var url = $(that).attr('action');
$.post(url, formData, function() {
// On success response do your stuff here
});
});
}
});

How do I return a boolean value for a form's "onsubmit" attribute depending on the success or error of an ajax call?

If my form is defined as follows:
<form action="myAction" method="post" id="input" target="_parent" onsubmit="doThis();">
and doThis() is part of the following script:
var result = false;
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
var status = false;
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
onSuccess(res);
},
error : function(e, msg, error) {
onError(e, msg, error);
}
});
return result;
}
function onError(e, msg, error) {
// do stuff if error
result = false;
}
function onSuccess(res) {
// do stuff if successful
result = true;
}
What I'm expecting is that if the ajax call is successful, onSuccess will set result to true, then doThis will return true and the form will submit. However, this does not happen. In fact, nothing happens.
My suspicion is that since the ajax call is asynchronous, doThis already returns a value (false) before the ajax transaction completes, so the return is always false. If that's the case, how do I modify my code so that it returns true or false depending on whether the ajax call is successful or not?
I think I can set async to false, but I keep on reading that callbacks are a better way to code than doing "async : false" --- so I was wondering what the best solution for this is.
EDIT:
I've put the following alerts in the onError and onSuccess functions:
function onError(e, msg, error) {
alert(e+" - "+msg+" - "+error);
result = false;
}
function onSuccess(res) {
alert("success");
result = true;
}
And running my code confirms that the logic passes through onSuccess.
Success is an AJAX event which is trigged after the AJAX completes http://api.jquery.com/Ajax_Events/ . So, what you are expecting is correct. Try adding some alerts to your code to see what each function is returning. like :
function onSuccess(res) {
// do stuff if successful
alert('Ajax success');
result = true;
}
r you sure that ajax request return success and go to function onSuccess(res) ?
you should add alert to know where the code goes. may be its goes to error : function(e, msg, error). alert what error msg saying?
I would suggest if possible you can go for Jquery Form Plugin. Instead of invoking an jquery ajax call
you can invoke ajaxForm or ajaxSubmitfunctions provided by that plugin. You can use these two functions just like an ajax call and it also supports success or error callback functions
Sample usage
$('#input').ajaxForm({
url: myUrl ,
success : function(response) {
// handle success
},
error : function() {
// handle error
}
});
Remove 'onsubmit' property.
<form action="myAction" method="post" id="input" target="_parent">
Instead use 'onclick' property. let's say your form is submitted by button or html element.
call $('.YourFormSubmitElement').onclick('doThis'). Note that if your has multiple form submission elements use class selector else if it is one use id selector.
Use the below function to submit the form.
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
$('#input').submit();
}
});
}
I think this should fix your problem.

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.

form submits before onsubmit function has finished

I'm calling the JavaScript function onsubmit of form but form has submit before finished the submit function.If I use the alert in the onsubmit function it finish the function first then submit the form.I used the settimeout function in place of alert but it didn't work.How can I submit the form after the onsubmit has complete.
function chat1close(name){
var abc;
abc=window.frames[0].test();
$.ajax({
type:'GET',
url:'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
}
});
document.getElementById("hello").innerHTML=" ";
alert("yes");
return true;
}
Add async: false to your ajax call. This will prevent it from executing the rest of the function until the call returns.
If chat1close is the function that is being executed on the form submit and you want the code to be executed synchronously then set the following option on the .ajax request:
async:false,
http://api.jquery.com/jQuery.ajax/
Easy way to do this:
var $form = jQuery("#the_form");
var should_submit = false;
$form.submit(function () {
if (should_submit)
return true;
$.post('some/async/thing', function () {
//This is an async callback that
//will set the should submit var to true and resubmit form.
should_submit = true;
$form.submit(); //will now submit normally because should_submit is true.
});
return false;
});
The form isn't sent before the function has finished, but you are making an asynchronous AJAX call in the function, and the form is sent before the AJAX response arrives and the success callback function is called.
The only way to do an AJAX call before the form is sent is to use a synchronous AJAX call, but that will freeze the browser while it's waiting for the response:
function chat1close(name){
var abc = window.frames[0].test();
$.ajax({
type: 'GET',
async: false,
url: 'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
document.getElementById("hello").innerHTML=" ";
alert("yes");
}
});
return true;
}
However, you can stop the form from being sent, and instead send the form after the AJAX response has arrived:
function chat1close(name){
var abc = window.frames[0].test();
$.ajax({
type: 'GET',
async: false,
url: 'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
document.getElementById("hello").innerHTML=" ";
alert("yes");
$('#IdOfTheForm')[0].submit();
}
});
return false;
}

Categories

Resources