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;
}
Related
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.
I am making an ajax call on submit button click event to check field validations server side.
When I get a validation fail, ajax response gives the proper error message, returns false, and stops the form to submit to the action url. But when I get a response of 'success', the form is still not submitting to the action url script.
Is this the case when return statement executes before ajax response?
And also why is the form not getting submitted?
Here is the code:
<input type="submit" onclick="return validate();" name="submit" value="Proceed" />
<script type="text/javascript">
var flag=false;
function validate(){
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
});
return flag;
}
</script>
one Way is
use async : false
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
async : false,
success: function (result) {
And also why are you returning the value outside the ajax function , return the value inside ajax success if you are not using async : false
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
return flag;
});
Ajax is asynchronous, so you should just pass a function to the function as an argument, and then execute it on success of the ajax call.
function my_callback() {
alert('done');
}
function validate(cb) {
$.ajax({
/* ... */
success: function() {
cb();
}
});
}
The function you pass to validate will be executed upon the success function 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.
I have a form that I want to ensure the paypal email address is valid before I submit. So i am making a jquery submit call like this
$('#new_user').submit(function(){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
return true;
}
}
});
but the problem is this call thats a second and the page already refreshes before the ajax is complete....if I put the return false at the end of the call I can see my json is correct but for some reason the way I have it now wont finish...any ideas on how to correct this
Just use preventDefault() immediately when the submit event is fired. Then wait for the response from paypal and then call submit() on the form.
$('#new_user').submit(function(e){
e.preventDefault();
var form = $(this); //save reference to form
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
form.unbind('submit'); //remove binding
form.submit(); //submit form
}
}
});
If you want to do something right away you would need to set async false in the request
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jquery ajax call taking too long or something
for some reason this ajax call
$('#new_user').submit(function(e){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
}
}
});
});
is still submitting the form even after prints out my error and my return false....why is that
$.ajax is a function call which defines an AJAX callback then and the .submit function ends. Separately (asynchronously) the AJAX call is made and your success function then returns false to basically nothing since .submit has already finished.
What you really want to do is halt the form submission process, waiting for the AJAX call to finish, then decide if it should continue. This can be achieved by completely stopping the form submission the first time, then manually resubmitting it once you've got the AJAX callback. Of course the trick is how do you know it's valid? You could throw a value on the submit element.
Example:
$('#new_user').submit(function(e){
var submitElem = $(this);
// Check for previous success
if (submitElem.data('valid') !== true) {
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false) {
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
} else {
// If successful, record validity and submit (allowing to continue)
submitElem
.data('valid', true)
.submit();
}
}
});
return false;
} else {
// Fall through
return true;
}
});