Having trouble with VueJS method not getting called after an asynchronous function callback?

I'm currently utilizing VueJS along with Stripe to create a form that can be submitted without needing to refresh the page. While the Stripe functionality is operational, the issue I'm facing doesn't seem to be directly related to Stripe.

The methods mentioned are all contained within the same component.

Once the form is filled out, a specific method is triggered to generate the card token (an async function).

tokenize : function(){
        console.log("tokenizing");

        this.stripe.createToken(this.card.number).then(function(result) {
            console.log(result);
            if (result.error) {
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
                console.log(result.error.message);
            } else {
                this.token = result.token.id;
                console.log(this.token);
                this.submit();

            }
        });
    },

Despite its presence, the submit function doesn't seem to be executed at all.

submit : function(){
        console.log(this.token); 
        console.log("here, token added");
        if(!document.getElementById('agreement').checked){
            this.$root.notify("You must agree to the terms.","danger");
            return;
        }
        console.log("about to send body");
        var body = {
            _token : this.$root.csrf,
            _method : "PUT",
            stripeToken : token,
            name : this.name,
            agreement : true,
        };
        console.log(body);
        console.log("pre axios");
        axios.put((window.location.origin + "/billing/" + this.$root.user.company_id),body).then(response => {
            this.my_billing = response.data;
            this.$root.notify("Card has been successfully added!","success");
            this.bEditMode = false;
        }).catch(error => { 
            this.$root.notify("Failed to add new card.","danger");
        });
    },

I've attempted setting an input tag with the value of the token, and utilizing a @change event on it, but that didn't trigger the function either upon value change.

Another attempt involved defining this.token as a computed property with setters and getters to call this.submit when the token is set. Unfortunately, this approach also failed to work.

Why isn't this method being invoked? While I've successfully called functions within async callbacks previously, is there a particular aspect that I might be overlooking? Are there any alternative solutions to circumvent this issue?

Answer №1

Ensure that you bind 'this' to your function for proper functionality.

this.stripe.createToken(this.card.number).then(function(result) {
....
}.bind(this));

By adding the bind(this) line, you should see a resolution to your issue. Failure to include bind(this) will result in the 'token' not being properly set in your data property.

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

Leveraging Vue 2.0 and webpack to integrate components from an npm package

As I venture into setting up a project with webpack and Vue 2.0, I encountered a slight hiccup when trying to incorporate components from npm packages (such as vue-parallax) into my project. Upon installing the package, everything seems to be in place, bu ...

Implement a React Component as a unique OverlayView within the Google Maps application

Utilizing the Google Maps JavaScript API V3, I have created a map with clustered and draggable map markers. Instead of relying on React libraries that interact with the google maps API, we chose to build our own solution due to limitations in drag function ...

knockout.js' $root leads to a page displaying nothing

Using the $root binding context is resulting in a blank page for me. Removing it allows the page to load properly. Causing blank page: <td><input data-bind="value: name" /></td> <td><select data-bind="options: $root.availableMe ...

Using Nested Maps in React to Fetch JSON Data

As someone who is relatively new to javascript and react, I've been honing my skills by practicing various techniques. Currently, I'm trying to work with JSON data to render multiple HTML blocks in a format resembling a basic schedule. Initially, ...

How can I display a pattern using Javascript?

Can you help me create a JavaScript program using a for loop to print a pattern with n number of asterisks and numbers like this: 1 2 3\n 4 5 6 \n 7 8 9 ...

Merge two arrays of the same size to create a single array of strings

Looking to merge the values of two equal-sized arrays and create a third array like the one shown below. I'm in need of guidance as I have not been able to locate a built-in JavaScript method for this specific task. The goal is to construct an array o ...

Using intricate document text as the input parameter in Vue: A guide

I am currently working with this Vue code snippet: <script> var starting_point = '{{ form.content.data }}'; vm = new Vue({ el: '#editor', data: { input: starting_point }, computed: { compiledMarkdown: function () ...

Manipulating values within a multidimensional array using JavaScript

I am attempting to populate a multidimensional array with data from a JSON file. The issue I am facing is that I am unable to update the content in the array: if(j>i && hoursYy == hoursY && secondsX == secondsXx){ wocheArray[i].count = wocheArray[i] ...

Reducing an array group using index in JavaScript: A beginner's guide

Do you have coding questions? Check out this sample array group: myArray = { tab1 : [], tab2 : [], tab3 : [], tab4 : [] } I'm looking to always retain the first tab (tab1) and an additional tab based on an index (ranging from 2 to 4) For instance, ...

triggering e.stopImmediatePropagation() within an onclick event handler

Is there a way to retrieve the event object from an onclick attribute? I attempted the following: <a href="something.html" onclick="function(e){e.stopImmediatePropagation();}">Click me</a> In addition, I tried this: <a href="something.ht ...

Before you start interactivity in three.js, you will be presented with a classic

Recently, I incorporated a 3D WebGL viewer into my website, but I encountered a minor problem. Although everything functions properly and I am able to manipulate the object, there is a brief moment of a black screen upon loading the page before moving the ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

The word 'function' is not defined in this React Component

Recently delving into the world of React, I decided to create a simple timer application. However, I encountered an error message upon running the code: (Line 40: 'timeDisplay' is not defined no-undef) class Home extends React.Component { ...

Generating a three-dimensional sphere from flat coordinates with the help of sine and cosine functions

I am trying to achieve mapping a set of 2D coordinates to a 3D surface of a sphere. To accomplish this, I am starting with an array of xy coordinates. Using the following loops, I am generating 20*20 xy coordinates ranging from 0 to 1 on each axis: var p ...

How can I incorporate a custom function in Robo3T?

After installing Robo3T (previously known as robomongo), a GUI for mongo db, I wanted to add a custom function to retrieve the last N documents in normal order. The query statement I used was: db.getCollection('i1801').find().skip(db.getCollecti ...

`Is it more effective to define an array outside of a component or inside of a component in React?`

Exterior to a unit const somevalue = [1, 2, 3, 4, 5, 6]; const Unit = () => { return ( <div> {somevalue.map((value) => <span>{value}</span>)} </div> ); }; export default Unit; Interior to a unit const Unit ...

New properties are not being successfully added to Passport Profiles

I am currently utilizing Passport OAuth2.0 with Google as my provider and encountering an unusual syntax issue. The structure of my authentication setup is as follows: passport.use(new GoogleStrategy({ clientID: GOOGLE_CLIENT_ID, clientSecret: GO ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

What is the method for obtaining receipt numbers in sequential order, such as the format AB0810001?

Is AB the receipt code that should remain constant followed by the current date (08) and 10001 as the receipt number? ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...