How to make a form awaiting ajax to complete before submitting it?

So, there is a form that I want to submit only when the condition is checked from the database using ajax. I use the preventDefault() method if the condition is true, i.e. If the user is not resident, the variable is set to true in the ajax successs function and preventDefault() receives a call, however, the form is always submitted. It did not wait for ajax to complete, even if async was set to false. Here is 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(); } }); 
+6
source share
1 answer

that won't work. Success will trigger after :

 if(not_resident){ e.preventDefault(); } 

How is it asynchronous? You always need to cancel the button click and then submit the form after successful success:

 $('#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(); }); 
+5
source

Source: https://habr.com/ru/post/948701/


All Articles