0

In my view, I need to do some extra "form validation" with my backend (called with $http). To abort or trigger the form sending, I need to wait for the promise returned by $http to finish.

$('#myForm').submit(function() {
    ...
   $http(...).success(function(data) {
      if (data.condition){
          //send the form by returning true
          return true;
      } else {
          //stay on this page by returning false
          return false;
   });

   //what should I return here ?? 
}

In general, how do we wait/block for a promise to finish, such as the one returned by the $http() function?

mjhm
  • 16,497
  • 10
  • 44
  • 55
Stéphane Piette
  • 5,341
  • 6
  • 34
  • 50
  • You can't. Return `false` always and submit the form data manually using AJAX if your validation allows it. – DCoder Apr 10 '14 at 09:01
  • The question was more about blocking for a promise than sending the form, so reopen ? – Stéphane Piette Apr 11 '14 at 12:51
  • I think you need to read the accepted answer to that question carefully; see that in that answer, the form is initially never submitted, but if the callback is successful, the callback submits the form `$("#someForm")[0].submit();` – Erwin Bolwidt Apr 11 '14 at 13:15

2 Answers2

2

Usually, the answer would be that should return the promise that was created via $http. However in the case of eventHandlers, you can call preventDefault() and then submit() explicitly.

var form = $('#myForm');
form.submit(function(e) {
   e.preventDefault(); // prevent submit
   $http(...).success(function(data) {
      if (data.condition){
          //send the form by explicit submit
          form.submit();
      }
   });
}

Note, this works just as well with very minor modifications in new browsers without jQuery.

On a side note, good angular practices discourage this sort of thing - you should put presentation logic in directives and not call DOM methods directly like that. The presentation "does not decide" about the fate of the page. It delegates via ng-click to a scope method.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
2

Promises don't make your code synchronous. AJAX is still asynchronous. You need to asynchronously handle your code.

So validate your code like you would validate with classic AJAX code.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • 8
    If the answer is no, please just say no. It's so goddamn frustrating to be searching the internet for an answer, and no one will say it straight. – Ethan Reesor Aug 30 '15 at 02:44