Is it possible for a form submission through javascript to disrupt existing axios requests?

I am facing a peculiar issue reported by my users, but I have never encountered it myself because I cannot replicate it.

In my vue.js component, there are two HTML forms. The first form is filled out by the user and upon submission, a function is triggered which makes two axios calls and then automatically submits the second form. This second form is a standard PayPal form that redirects the user to the PayPal website. Below are snippets of the code:

The doLogging() function is responsible for writing to a file on a different server. On the other hand, the doMail() function sends an email and also writes to another file.

Users are always redirected to the PayPal site without any issues. However, sometimes both logging and emails are successful, while other times neither of them occur. It seems like the axios calls intermittently fail to execute.

Here is an excerpt of the HTML code:

<form @submit.prevent="processRegistration()">
  <button type="submit"
    class="button is-info">Ready to pay with PayPal
  </button>
  ... other form elements ...
</form>

<form id="paypalForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" class="hidden">
   ... paypal form elements ...
   <input type="submit" value="Pay with PayPal"/>
</form>

And here are simplified versions of the functions being called:

 processRegistration() {
    this.doLogging();
    this.doMail();

    let paypalForm = document.getElementById('paypalForm');
    paypalForm.submit();
 }

async doLogging() {   // log info to a file
  let headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};
  try {
    await axios.post('https://logging.xxx.com/logger.php', this.stuff, {headers: headers});
  } catch (e) {
    console.log(e);
  }
}, 


async doMail() {  / send email and log info to a file
    let headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};
    try {
        await axios.post('/email.log.php', this.otherStuff, {headers: headers});
    } catch (e) {
        console.log(e);
    }
 },

Answer №1

It is important to note that the promise in doLogging() and doMail() may not be resolved in time for the paypal form submission. To resolve this issue, one solution is to await both functions (and make processRegistration() async).

async processRegistration() {
    await this.doLogging();
    await this.doMail();

    let paypalForm = document.getElementById('paypalForm');
    paypalForm.submit();
 }

By restructuring the code in this way, doMail() will wait for doLogging() to complete before allowing paypalForm.submit() to proceed. Alternatively, chaining could also be utilized as another option.

While this method may not be the most elegant approach, it effectively accomplishes the task at hand.

Answer №2

Having delved deeper into the realm of Promises, I have devised my own solution to the issue at hand. Recognizing that the doLogging() and doMail() tasks can run concurrently, I opted for utilizing Promise.all() to ensure their completion before proceeding with the PayPal transaction.

doLogging() {
 let headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};
 return axios.post('https://logging.xxx.com/logger.php', this.stuff, {headers: headers});
},

doMail() {
 let headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};
 return axios.post('/email.php', this.otherStuff, {headers: headers});
},

submitToPayPal() {
 let paypalForm = document.getElementById('paypalForm');
 paypalForm.submit();
},

processMembership() {
 let log = this.doLogging();
 let mail = this.doMailToDancer();

 Promise.all([log, mail])
  .then(this.submitToPayPal())
  .catch(error => {
   console.log(error.message)
  });
},`

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

Retrieve information from a variety of selected checkboxes

Is there a way to retrieve the values of check boxes that are generated dynamically? @ $db = mysql_connect("abc", "abc", ""); mysql_select_db("abc"); $strSQL = "SELECT * FROM student"; ...

What could be causing the Material-UI Appbar onLeftIconButtonTouchTap function to malfunction?

I am currently learning React-Redux and Material-UI. I'm working on creating a Sample App, but I'm facing some difficulties. I need help in improving my code. Specifically, I am trying to make the Drawer open when the Material-UI AppBar's on ...

Retrieve the stylesheet based on the presence of a specific class

Is there a way to dynamically add a CSS stylesheet based on the presence of a specific class on a page? For example, instead of checking the time and loading different stylesheets, I want to load different stylesheets depending on the class present in the ...

Issue with Angular: PDF rendering delayed until window resize

Recently, I encountered an issue with rendering a PDF in Chrome while using an AJAX call with Angular. Strangely, the PDF would only show up in the browser if I resized the window or opened the console. Surprisingly, everything worked fine in Firefox. Jav ...

Exploring SVGO CLI: A guide to inspecting SVGs across various directories

Currently, I am utilizing the SVGO CLI script to transform some icons within my project. Specifically, these icons are located in two separate folders - assets/icons/dark-mode and assets/icons/light-mode. My goal is to navigate through both of these folder ...

How can I log an object definition and text in the same console.log statement?

Looking for a way to correctly display "obj" in the same string as "note." Here's my JavaScript code: console.log(obj);// [query: "wordOfTheDay"] console.log(note + " : " + obj ); // obj does not show up I want to ensure that "obj" displays properly ...

Refining an object by using a parent key as a filter criterion (JavaScript)

Refined JSON Data Check out this unfiltered JSON object that I am working with: info = [ {id: 1, name: "home", parent: 0, active: 1, order: 0}, {id: 2, name: "dashboard", parent: 0, active: 1, order: 1}, {id: 3, name: & ...

Tips for retrieving the value of the current point in a dynamic line chart with Chart JS using JavaScript

Is there a way to continually track and log the current value of a progressive line chart in Chart JS every second for the full 20-second animation duration using javascript? I am wondering if setInterval would be an effective method for achieving this, ...

Ensuring validation with Javascript upon submitting a form

Hey there, I'm looking to validate field values before submitting a form. Here's the code I have: <table width="600" border="0" align="left"> <tr> <script type="text/javascript"> function previewPrint() { var RegNumber = docum ...

Clicking on an iframe activates the loading of the displayed page

I'm attempting to create a functionality where clicking on an iframe will load the page it is displaying. I experimented with placing it within an tag, but that didn't produce the desired result. The effect I'm aiming for is similar to zoom ...

Error message 'AVV_ERR_PLUGIN_NOT_VALID' encountered within fastify

I've encountered an issue while setting up the environmental variables in my fastify - react app. Can someone help me with resolving the 'AVV_ERR_PLUGIN_NOT_VALID' error that I'm receiving for the following fastify code? Your assistance ...

A guide on populating a dropdown menu with spring and hibernate in JSP

I'm a newcomer here and seeking ideas from you all. I have 4 dropdown lists and want to populate one select box based on the selection made in another select box using database values. I have already set up the database, but unsure how to proceed. Any ...

Sorting arrays in javascript

My JavaScript array is structured like this: var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]] I am looking to organize and sort them based on the first value in each pair: 1,id_1001 2,id_1002 3,id_1003 4,id_1004 5,id_1005 ...

Enhance the functionality of NodeJS core applications

I recently attempted to modify some custom functions in the FS module of NodeJS, which is an integral part of NodeJS' core modules. The specific file I targeted was fs.js, located in /usr/lib/nodejs. However, despite making changes to the code, I noti ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

The default zoom setting for ng-map is overly magnified when paired with the zoom-to-include-markers="true" feature

When using maps, I encountered an issue where having only one marker with the zoom-to-include-markers="true" attribute resulted in the map being overly zoomed in. Regardless of how I adjusted the zoom attribute, the result looked like this: https://i.sstat ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

The property 'clone' is undefined and cannot be read

Currently, I am using Fullcalendar to update events. My goal is to execute an ajax callback to retrieve the edited version of a specific event. The endpoint for this request should be at /controls/:id/edit. To achieve this functionality, I have implemented ...

Modify the background color of paragraph using JavaScript based on the outcome

I am trying to update the background color of a search result in a paragraph tag based on a condition where the value of a variable is greater than 1. I believe this can be achieved using an if statement. Below is the code snippet I am currently working on ...