So there is a form that i want to submit only when a condition is verified from the database using ajax. I am using preventDefault()
method if the condition is true i.e. if a user is not a resident, a variable is set to true in ajax successs function
and preventDefault()
gets called, however, when doing this, the form always submits. It doesn't wait for the ajax to finish even when async is set to false.
Here's the code.
$('#button').click(function(e) {
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
var not_resident = false;
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
not_resident = true;
},
dataType: 'html'
});
}
if(not_resident){
e.preventDefault();
}
});
You may need to run certain code only after all Ajax requests have completed when working with many Ajax requests. To do this, use the when function in jQuery. It takes any number of arguments and executes once all of the parameter functions have been performed.
With the help of the event. preventDefault() method the event is to be stopped the form execution.
Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.
A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.
that won't work. Success will fire after:
if(not_resident){
e.preventDefault();
}
As it's asynchronous. You need to always cancel the button click then submit the form once success is hit:
$('#button').click(function(e) {
var $form = $(this).closest('form');
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
$form.submit();
},
dataType: 'html'
});
}
e.preventDefault();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With