javascriptangularjspostform-submitng-submit

AngularJS - Run and wait for an asynchronous function before form submit action


I'm tying to run a angular function before the user is posted to the payment provider. The form to the payment provider looks like this:

<form action="UrlToPaymentProvider" method="POST">
   <input type="hidden" name="formKeys />
   <input type="submit" />
</form>

AngularJS controller file:

$scope.memberRedirectedToPaymentProvider = function () {
     console.log("Member is redirected");
     $http.post("/my url", {
         orderKey: $scope.model.Order.Key,
     });
}

I can see that my log outputs the value but the post is not. I've debugged and the post works if I remove action="UrlToPaymentProvider" method="POST" on the form element.


Solution

  • I understand that you try to mix a sync & async call on form submit. You can mix a synchronous form send with an AngularJS function like in this demo fiddle. The default form submit is prevented by e.preventDefault(); once your XHR request was finished the form will get submited by native JavaScript document.getElementById("myForm").submit();.

    View

    <div ng-controller="MyCtrl">
      <form method="post" ng-submit="send($event)" action="someURL" id="myForm">
        <input type="hidden" name="formKeys">
        <input type="submit">
      </form>
    </div>
    

    AngularJS application

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope, $http) {
    
        $scope.send = function (e) {
    
          //prevent default form send
          e.preventDefault();
    
          //example request
          $http({
            method: 'GET',
            url: 'https://jsonplaceholder.typicode.com/posts'
          }).then(function(response) {
             //manually submit your form once your async. logic has been procceded.
             document.getElementById("myForm").submit();
          });
        };
    });