Submit HTML form using AngularJS

The payment gateway I’m integrating with requires a post from a form to navigate to their payment page. Some of the information I need to post is dependent on the results from a call to my back end server.

My first attempt was to invoke my controller from a regular JavaScript function called in onsubmit. However, as all $http calls in AngularJS are asynchronous there was no way to wait for the result of my back end server call before either allowing or blocking submission of the form.

The approach that worked was to create the form without an action or method. When the ‘submit’ button is clicked, the controller function (createPaymentAndNavigate) is called. This does the call to the back end, in the success callback sets the action and method on the form, and then submits the form.

HTML

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

Success callback in AngularJS controller

var bookingForm = document.getElementById('bookingForm')
bookingForm.action = "https://www.example.com/xyz/process.trans";
bookingForm.method = "POST";
bookingForm.submit();
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *