Vue.js - displaying alert and redirecting after submitting axios form

I have a form that is functioning properly and inserting data correctly. However, if the user clicks the submit button multiple times, the data gets inserted multiple times. To prevent this, I want to redirect the user to another page and display a success or error message. Currently, I am using Axios to handle the form submission. Below, I have included the Axios code with a then response and catch error, but I am struggling to display these messages in the HTML:

reserve() {
            // this.form.post('../api/comment')
            axios.post('../api/reserve',{
                property_id:1,
                reserve_start:this.date,
                reserve_end:this.date2,
            }).then(response => {
                self.message = 'Data has been successfully entered'
            })
                .catch(error => {
                    self.message = 'Error: Data could not be entered'
                })

Here is the markup for my form:

<form @submit.prevent="reserve()"  id="myForm"  class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed">

Answer №1

Redirecting in a method after making an axios call is quite simple and direct.

You can achieve it like this:

reserve() {
// this.form.post('../api/comment')
  axios.post('../api/reserve',{
    property_id:1,
    reserve_start:this.date,
    reserve_end:this.date2,
  }).then(response => {
    this.$router.push('/routeToGoTo')      
  })
}
.catch(error => {
  self.message = 'Error'
})

If you want to pause everything until redirection, you can add an alert before router.push. The alert will pop up, user clicks ok, and then the page redirects.

alert("Something was done.")

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

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

What is the best way to retrieve the promise that encountered an error in the catch block while using async/await

I'm currently in the process of converting code that used .then/.catch to instead use async/await. One particular challenge I'm facing is how to access the original promise that fails within the catch block, for logging purposes. Here is the ori ...

Repeating X and Y Axis Labels on Highcharts

Highchart is new to me. I recently created a basic chart showing the count of males and females over the past five years. I have included a screenshot for reference. I am wondering if it's possible to remove duplicate labels from both axes? Below is ...

Vue main component fails to detect emitted events from child component

I am working on a website that will showcase multiple cards which expand when selected. Here is the code for the card component: <template> <v-card class="mx-auto" max-width="90%" min-height="6 ...

The modified navigation bar is not appearing in the display of the Laravel and Vue project

After creating a fresh Laravel project using the command laravel new projectname, I selected jetstream, inertia, api, dark, ssr as my preferences. However, when I made modifications to the navbar section in app.blade.php by adding an item on the left side ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Storing intricate items in a JavaScript database can be tricky. Using JSON.stringify() can sometimes lead to unexpected errors

In my project, I have a class called Player and a list of players named gameData. My goal is to save and retrieve this gameData from a database so that user information remains intact even after the bot restarts or crashes. However, when attempting to use ...

Creating a custom color palette with Material UI using ThemeProvider

Attempting to set a custom color for a Button using createMuiTheme and ThemeProvider has been successful with the primary and secondary palettes. However, when trying to utilize an alternate color such as "info", it does not seem to work as expected: http ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Tips for bringing in and adding an excel spreadsheet to a kendo grid with the help of JQuery

I am facing a challenge with my kendo grid as I am trying to incorporate an excel file into it. Specifically, I would like to import and add an excel file to my kendo grid. If, for instance, my kendo grid initially has 3 rows, after importing an excel file ...

What techniques can I employ in Angular to develop engaging widgets using plain HTML, without any Angular-specific elements?

I am currently developing a cutting-edge Angular application that serves as a training platform to offer online courses to users. Each course is essentially a set of "slides," which are HTML partials through which the user can navigate in order. These sli ...

Once upon a time in the land of Storybook, a mysterious error message appeared: "Invalid version. You must provide a string

I keep encountering an issue while attempting to set up storybook. Can anyone help me figure out what's causing this problem? npx storybook@latest init • Detecting project type. ✓ TypeError: Invalid version. Must be a string. Got type "obje ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

Display the results of the constantly changing JSON response

I am expecting to receive a dynamic JSON response based on the provided input. Here is an example: { results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c487c6d7b7c266b6765">[email protec ...

Serving files from a Node.js server and allowing users to download them in their browser

I am facing an issue with my file repository. When I access it through the browser, the file automatically downloads, which is fine. However, I want to make a request to my server and then serve the file result in the browser. Below is an example of the GE ...

What is the best way to send parameters to an event listener in a React component?

I am struggling with a component setup that looks like this: import React, { useEffect } from 'react'; const WindowFocusHandler = ({store}) => { // The store object is valid and working here useEffect(() => { window.addEventListene ...

Encountering an error when using the Vue 3 TypeScript Composition API for style binding with an asynchronous

I utilized nexttick alongside an async method to update a DOM element. However, I am encountering issues with returning the correct style type. An error message pops up stating: error TS2322: Type 'Promise<{ maxHeight: string; }>' is not ...

Issue with selecting multiple items in DataTables using the shift key

Currently, I am working with datatable 1.10 and have successfully created a table. However, I am unable to enable the multiple "shift select" functionality for its rows. Referring to the official DataTables documentation: The TableTools plugin offers fou ...