Submit Form when AJAX Call is done

Submit Form when AJAX Call is done

Hello,
i would like to do an API call when a form is submitted. The result should be stored as hidden input.
My Problem is, that the form is submitted just before the ajax call is ready.                       

Here are some simplified code snippets:

  1. $("#MyForm").submit(function(){
  2.     $.when( api_call() ).then( form_submit($(this)) );
  3.     console.log('Not Submitted');
  4.     return false;
  5. });
  6. function api_call() {
  7.     console.log('AJAX Call');
  8.     return $.ajax({ success: function(){
  9.             // Set hidden input field
  10.             console.log('AJAX Completed');
  11.         }
  12.     });
  13. }
  14. function form_submit(form) {
  15.     console.log('Submitted');
  16.     form.submit();
  17. }                

In my console log:


  1. AJAX Call
  2. Submitted
  3. Not Submitted
  4. AJAX Completed





So the direction is clear:
The ajax call is sent and the form is submitted before the ajax call is ready...

How can i solve this problem?


Regards