Michael Williams
Michael Williams

Reputation: 391

Call server synchronously with AngularJS before form submit

I'm integrating my AngularJS app with a payment gateway that requires a form to be submitted to kick-off the process to collect the users credit card details.

The flow is as follows:

  1. User fills in information in an HTML form.
  2. User clicks submit button.
  3. onsubmit JavaScript calls an AngularJS controller function that calls my server via $http and gets some information back.
  4. This information is used to populate hidden fields in the form.
  5. The form is submitted to the payment gateway site and the user enters their credit card details on that site.

For this process to work, I need the call to my server to return before I return true or false from onsubmit and allow the form to be submitted.

All the examples using promises ($q) ultimately lead to code that uses callbacks. How do I achieve the above flow with a synchronous call, or is there another way to achieve what I require?

function allowSubmit() {
        var scope = angular.element(document.querySelector( '#bookingForm' )).scope();

        try {
            var success = scope.createPayment();//createPayment is a method on my controller I need to synchronously call my backend with
            return success;
        } catch (e) {
        //log/alert
            return false;
        }
}


<form id="bookingForm" name="bookingForm" novalidate action=" https://www.example.com/xyz/process.trans" method="POST" onsubmit="return allowSubmit();" >
...
<button type="submit" class="btn btn-success btn-lg pull-right">Payment</button>
...
</form>

Upvotes: 1

Views: 1155

Answers (1)

Michael Williams
Michael Williams

Reputation: 391

The solution looks to be: Create the form without an action or method, then set them and submit on callback from server in the controller.

<form id="bookingForm" name="bookingForm" novalidate >
...
<button class="btn btn-success btn-lg pull-right" ng-click="createPaymentAndNavigate(bookingForm.$valid)">Payment</button>
...
</form>

//In server callback on controller
var bookingForm = document.getElementById('bookingForm')
bookingForm.action = "https://www.example.com/xyz/process.trans";
bookingForm.method = "POST";
bookingForm.submit();

Upvotes: 2

Related Questions