user943369 user943369 -4 years ago 190
AngularJS Question

AngularJs - Run a asynchronous function before form submit to 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" />

AngularJS controller file:

$scope.memberRedirectedToPaymentProvider = function () {
console.log("Member is redirected");
$"/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.

Answer Source

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. First 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();.


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

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope, $http) {
    $scope.send = function (e) {

      //prevent default form send

      //example request
        method: 'GET',
        url: ''
      }).then(function(response) {
         //manually submit your form once your async. logic has been procceded.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download