What is the best way to show a modal after a successful ajax response in vue?

I have a Vue component structured like this:

<template>
    ...
    <b-modal id="modalInvoice" size="lg"  title="Invoice">
        <Invoice/>
        <div slot="modal-footer" class="w-100"> 
            <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
                <i class="fa fa-print"></i> Print
            </b-btn>
        </div>
    </b-modal>

    ...
        <b-btn variant="warning" class="btn-square mt-2" v-b-modal.modalInvoice @click="checkout()"><i class="fa fa-credit-card-alt"></i>Checkout</b-btn>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            checkout() {
                var request = new Request(ApiUrl.orders, {
                    method: 'post',
                    body: JSON.stringify(this.$session.get(SessionKey.Cart)),
                    headers: new Headers({
                        'Authorization': 'bearer ' + this.$session.get(SessionKeys.ApiToken),
                        'Content-Type': 'application/json'
                    })
                });
                fetch(request).then(r=> r.json())
                    .then(r=> {
                        this.items = r.data
                        // Show modal here
                    })
                    .catch(e=>console.log(e));
            }
        }
    }
</script>

Currently, the modal shows immediately when clicking the checkout button. I would like it to only show after the AJAX response is successful.

How can I achieve this behavior?

Answer №1

Implement the use of v-model to manage the visibility of the modal:

<b-modal id="modalInvoice" size="lg" title="Invoice" v-model="show">
    <Invoice/>
    <div slot="modal-footer" class="w-100"> 
        <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
            <i class="fa fa-print"></i> Print
        </b-btn>
    </div>
</b-modal>

This allows you to explicitly control the show property when the fetch operation is completed:

<script>
    ...
    export default {
        ...
        // define a data property for the v-model binding
        data () {
            return {
                 show: false
            }
        },
        methods: {
            checkout() {
                var request = new Request(ApiUrl.orders, {
                    method: 'post',
                    body: JSON.stringify(this.$session.get(SessionKey.Cart)),
                    headers: new Headers({
                        'Authorization': 'bearer ' + this.$session.get(SessionKeys.ApiToken),
                        'Content-Type': 'application/json'
                    })
                });
                fetch(request).then(r => r.json())
                    .then(r => {
                        this.items = r.data;
                        // set show to true to display the modal
                        this.show = true;
                    })
                    .catch(e => console.log(e));
            }
        }
    }
</script>

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

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

When the height of the html and body is set to 100%, ScrollY/ScrollTop is unable to function properly

Utilizing height: 100% and overflow: auto on html/body has helped me fix a scrolling issue in Chrome. However, I've noticed that ScrollY and ScrollTop always return 0 now. Is there a way to determine the scroll position in this scenario? Here is the ...

steps to attach click event to row of a-table component in ant design vue

Here is the code snippet for the table I am working on. I have imported a-table from antd. To enable click functionality to route to a details page from this listing page, an additional td can be added. <a-table :columns="companiesColumns" :d ...

Disordered city names discovered while conducting reverse geocoding with a maps API in a loop

I am currently working on reverse geo-coding a series of coordinates using a for loop in node.js. After each iteration, I store the result in an array. However, when I try to display the array in my angular front-end or check it in the console, the order o ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...

Adjust the package.json file for deployment

I've encountered a problem while attempting to deploy my nodejs application on Heroku. Despite following the documentation and modifying files in the root directory, I have not been successful. Below is the structure of my package.json file: { ...

The iPad screen displays the image in a rotated position while it remains

Recently, I developed a mini test website that enables users to upload pictures and immediately see them without navigating back to the server. It seemed quite simple at first. $('input').on('change', function () { var file = this. ...

Obtaining the server reference in deployd (Node.js) is a straightforward process that involves accessing

I am currently working with deployd and I require access to the current server object within a background thread. This particular situation does not involve any requests, responses, or sessions. Is there a method available to obtain this reference? ...

Calculate the total value of selected checkboxes in every row of the table

I am looking to calculate the total sum of checkboxes for each row in a table Javascript : For Sum $('input[type="checkbox"]').change(function() { var total = 0; $('#mytable tr').each(functi ...

"Establishing a connection between my Vue component and Node server: A step-by-step guide

Greetings everyone, I am currently in the process of developing a Single Page Application (SPA) chat application. I am utilizing Vuejs for the front end and Laravel 5.4 for my backend API. In order to create a real-time communication experience, I have set ...

Error: Unable to locate module '@mui/icons-material/FileDownload'

I have successfully installed both @material-ui/core and @material-ui/icons. Currently, I am attempting to import the icon "FileDownloadIcon" from Material icons. For installing "@material-ui/core", I used the following command: npm i ...

personalized popup notification following execution of query

I have an anchor tag that when clicked, it takes the ID and runs a query to delete rows. Currently, a JavaScript alert box appears with a successful submission message (LOCAL host says:.....). However, I would like to display a custom message or modal popu ...

There seems to be an issue with the Alexa skill's ability to provide a response after another

I am currently developing an Alexa skill that involves a multi-step dialog where the user needs to respond to several questions one after the other. To begin, I am trying to kick things off by implementing a single slot prompt. I am checking if the slot is ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

Fatal syntax error encountered when attempting to define a JavaScript object

Hey, I'm just starting out with JavaScript and I'm encountering a syntax error with the getValue() function in the code below. Can someone please assist me in solving it? let obj = { x:1, function getValue(){ console.log("hello") } } ...

What is the most efficient way to organize a list within an object using functional programming, taking into account varying criteria for sorting depending on

In this scenario, we have an 'api_fetchData' function that retrieves data from the server. Depending on the route, the data can be in the form of a table or a tree structure. There are two states that need to be updated based on the received data ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...