Executing AngularJS - Ensuring an asynchronous function completes before submitting a form

I am trying to execute an angular function before the user is directed to the payment provider. The form for the payment provider appears as follows:

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

Here is the AngularJS controller file:

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

Although my console log displays the value, the post request does not seem to work. Upon debugging, I discovered that the post request works if I remove

action="UrlToPaymentProvider" method="POST"
from the form element.

Answer №1

Attempting to combine synchronous and asynchronous calls during form submission can be tricky. You can achieve this by incorporating an AngularJS function, as demonstrated in this interactive example. By using e.preventDefault();, the default form submission is prevented until your XHR request is completed, at which point the form will be submitted using native JavaScript with

document.getElementById("myForm").submit();
.

Implementation Example

<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 Setup

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

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

    $scope.send = function (e) {

      //prevent default form submit
      e.preventDefault();

      //sample request
      $http({
        method: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts'
      }).then(function(response) {
         //trigger form submission after async operations are completed
         document.getElementById("myForm").submit();
      });
    };
});

Answer №2

You might want to consider implementing something along these lines:

<form ng-submit="submitForm()" >
    <input />
    ....
</form>

and within the controller :

$scope.submitForm = function() {

     //execute your custom logic here

     $http.post('urlToPost', $scope.formData)
     .success(function(data, status, headers, config) {
        console.log("Successful response received")
     })
     .error(function(data, status, headers, config) {
        console.log("Error in response received")
     });
 }

Answer №3

Instead of utilizing the action attribute in a form, you have the option to use ng-submit.

<form name="myForm" ng-submit="memberRedirectedToPaymentProvider()">
<input type="hidden" name="formKeys />
...

<input type="submit" />
</form>

To initiate an AJAX POST request, you can employ the angular $http service and its post method.

$scope.memberRedirectedToPaymentProvider = function () {
     console.log("Member has been redirected");
     var url = "/myurl";
     var data = {
         orderKey: $scope.model.Order.Key
     };
     $http.post("/myurl", data).success(function(data, status) {
            $scope.response = data;
     })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to selectively import specific modules in three.js using ES6 syntax

I recently integrated the three.js library using NPM with the goal of leveraging its new ES6 modular architecture. This design allows for selective importation of specific modules as outlined in this resource: Threejs - Import via modules. For bundling an ...

Configuring a Themeforest HTML template with Vue and Laravel. Issue encountered when attempting to load JS files using router.push

Currently working on my first frontend website using Vue and Laravel. I decided to purchase a template from Themeforest which is based on HTML/CSS/JavaScript. The setup of Vue and Vue Router with Laravel is complete and everything seems to be functioning ...

Struggles with integrating a disappearing navigation bar when scrolling - JavaScript

I've been struggling with a fixed position navbar on my blog and I'm attempting to incorporate basic JS to hide the navbar while scrolling down and have it reappear when scrolling up. You can find the code snippet I'm trying to implement in ...

The onselect attribute within the HTML <option></option> element allows you to trigger an event when a user selects an

Hello! I'm currently working with a list that has an onChange event within the <select>... tag. In the code snippet below, you can see that there are two options. The option labeled 55-rene has the attribute selected="selected", making it automa ...

Creating a State in Typescript Vuex with Accessors: A Step-by-Step Guide

Within the vuex store, I am attempting to initialize a state called _token. However, when I try to access the property within the same class, I am encountering an error message stating that the setter for _token is not defined. Can anyone shed light on why ...

Looking to $post the content of a text field, rather than the selected option from a dropdown menu

<select name="duration" id="duration" > <option value="0" >Choose Duration *</option> <option value="3000" >6 Months</option> <option value="6000" >12 Months</option> <option valu ...

The State in the useEffect hook does not update instantly

After conducting some research, I discovered that useState operates asynchronously. However, I am still struggling to resolve my specific issue. My task involves fetching data from an API, but the state is only updated during the second render. Furthermore ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

Formatting DateTime in Angular from an API

After confirming that the back end Java Rest API is indeed sending the correct date time format: 2018-05-17 19:08:25.203 Upon arrival to my Angular service, the date format mysteriously transforms into a large number: 1526555305203 The code snippet bel ...

The JQuery function .html() fails to include all the HTML content retrieved from a JSON response

I've created some HTML using PHP's json_encode(), and it looks like this: ob_start(); if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); get_template_part( 'template-par ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

Unusual outcome observed when inputting a random number into HTML using JavaScript

In my HTML file, I am trying to input a number within 50% of a target level into the "Attribute" field. Here is the code: <!DOCTYPE html> <html> <body> <input type = "number" name = "playerLevel" onchan ...

React-Query will not automatically refetch data on mount when using an invalidated query

I made sure my components do not always refetch when they mount and already have the query in the cache by implementing the following solution: export const App = ({ props }) => { const queryClient = new QueryClient({ defaultOptions: { queri ...

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...

"Placing geotags on the map for every individual location on Google Maps

I am currently using code that was not written by me to generate a Polyline on a Google map based on longitude and latitude entries from my database. It is functioning correctly at the moment. My goal is to enhance it by adding a marker for each location a ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

Activate search bar by clicking on it

I am currently attempting a basic jQuery example to expand a search bar on mouse click, but for some reason, my code is not working as expected. I have a simple jQuery function to display the input field when the button with the class "expand" is clicked, ...

Using ASP.NET Server Controls to Toggle Textbox Visibility Based on Dropdown Selection

What is the optimal method for displaying or hiding a textbox or an entire div section based on a user's selection from a dropdown menu? I am uncertain if this can be achieved with server controls, so would it require using standard client-side HTML c ...

Error: The variable "$this" has not been defined in the AJAX function

Recently, I've been delving into the world of javascript and ajax. I'm trying to create a dynamic select option list similar to this: https://i.sstatic.net/qELIf.png However, when attempting to compile using Google Chrome Developer tools (F12), ...

Learn how to create a button that will only submit a value when clicked using Node.js and EJS

Currently in my ejs file, I have a button that sends a value to app.js instantly when the program runs. However, I want it to only submit the value when clicked by the user. <% notesArray.forEach((note,i) =>{ %> <div class="note"> ...