The Vuebootstrap component b-alert is failing to display the dynamic message from the response variable returned by the axios

I have utilized Vue Bootstrap for styling, and I am in the process of creating a user registration form. Upon submission of the form by the user, Axios will make a POST request to the API. If the call is successful, the API will return a success response; otherwise, an error message will be included in the response. My goal is to capture this response and display an alert on the webpage. The current issue I am facing is that the alert message appears for the first couple of submissions but then stops showing up. I am eager to learn how to bind data in Vue effectively. Thank you.

<template>
<div>
  <div  class="container1">
  <b-card
    text-variant="Dark"
    header="Please Register"
    header-text-variant="white"
    class="shadow p-3 mb-5 bg-white rounded"
    header-class="card-header"
  >
      <b-form @submit.prevent="onSubmit" v-if="show">
        <b-form-group id="input-group-2" label="User Name" label-for="input-2"
                      style="text-align: left">
        <b-form-input
          id="input-3"
          v-model="form.name"
          placeholder="Enter User name"
          required
          ref="name"
        ></b-form-input>
          </b-form-group>
      <b-form-group
        id="input-group-1"
        label="Email address"
        label-for="input-1"
        style="text-align: left"
      >
        <b-form-input
          id="input-1"
          v-model="form.email"
          type="email"
          placeholder="Enter email"
          required
          ref="email"
        ></b-form-input>
      </b-form-group>

      <b-form-group id="input-group-2" label="Password" label-for="input-2"
      description="Password should be more than 8 characters."
      style="text-align: left">
        <b-form-input
          id="input-2"
          v-model="form.password"
          placeholder="Enter Password"
          required
          ref="password"
          type="password"
        ></b-form-input>
      </b-form-group>
      <b-button @click="showDismissibleAlert=true"
                class="submit_button" type="submit">Submit</b-button>
    </b-form>
  </b-card>
    </div>
  <div>
    <b-alert
      v-model="showDismissibleAlert"
      variant="danger"
      dismissible
      fade
      :show="showDismissibleAlert"
      @dismissed="showDismissibleAlert=false"
    >
      {{ showalert }}
    </b-alert>
  </div>
</div>
</template>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600&family=Poppins&display=swap');

.container1 {
  justify-content: center;
  display: flex;
  margin-top: 10%;
  font-family: 'Poppins', sans-serif;
}
.card-header {
  background-color: #12858b;
}
.submit_button {
  background-color: #12858b;
}

.form-control::placeholder {
  opacity: 35%;
}

</style>

<script>
import axios from 'axios';

export default {
  el: '#showalert',
  name: 'LoginForm.vue',
  data() {
    return {
      form: {
        showalert: '',
        name: '',
        email: '',
        password: '',
        showDismissibleAlert: false,
      },
      show: true,
    };
  },
  methods: {
    async onSubmit(event) {
      const path = 'http://127.0.0.1:5000/register';
      axios.post(path, {
        user_name: this.form.name,
        email: this.form.email,
        password: this.form.password,
      })
        .then(() => {
          const result = 'Success!';
          console.log(result);
        })
        .catch((error) => {
          if (error.response) {
            // alert(error.response.data);
            this.showalert = error.response.data;
            console.log(error.response.data);
          }
        });
      event.preventDefault();
      this.form.name = '';
      this.form.email = '';
      this.form.password = '';
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
  },
};
</script>

Answer №1

After making some adjustments to the variables in the form data, I was able to get it working properly. Here is what the code looks like now:

<b-alert
      v-model="showDismissibleAlert"
      variant="danger"
      dismissible
      fade
      @dismissed="showDismissibleAlert=false"
      class="error-alert-message"
    >
      {{ form.showalert }}
    </b-alert>

&

.catch((error) => {
          if (error.response) {
            this.showDismissibleAlert = true;
            this.form.showalert = error.response.data;
            this.form.image1 = false;
            this.image2 = true;
            console.log(error.response.data);

Answer №2

Discover the solution you seek within the official documentation.

Avoid utilizing the show prop while implementing v-model.

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 make the dropdown menu in Material UI Select have a horizontal scroll bar?

I've run into an issue in my project with the material ui Select component. The dropdown contents are too long and don't fit properly. https://i.sstatic.net/DNCTf.png To solve this problem, I tried adding a horizontal scroll to the dropdown men ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Take away the outline of the input field and customize the placeholder text color in Buefy

I'd like to remove the borders, keeping only the bottom border. Additionally, I need help changing the color of the placeholder. The CSS I have used seems to be causing an odd appearance at the edge of the input field. <b-field label= ...

Send the checkbox value using ajax, jquery, and php

Hey everyone, I'm facing an issue and need some help. I am trying to send the value of a checkbox via AJAX to a PHP file. My question: I want to pass the checkbox value regardless of whether it is checked or not. If it is checked, then the value "tr ...

Difficulty in dynamically updating custom attributes data in a popover

I am attempting to dynamically insert text into a Bootstrap 3 Popover data-content="" on this demo. My goal is to update the text in the data-content="" attribute by clicking different buttons. I have tried doing this using the following code: $("#poper") ...

Guide to retrieving the width measurement of a troika-three-text element

Is there a way to retrieve the dimensions (width and height) of a Text object from troika-three-text library? import { Text } from 'troika-three-text' // Instantiate Text object: const myText = new Text() myScene.add(myText) // Customize proper ...

Guide to ensuring jQuery Ajax requests are fully processed with WatiN

Currently, I am in the process of developing WatiN tests to evaluate an Ajax web application. However, I have encountered a timing issue with Ajax requests. My main objective is to ensure that WatiN waits for the Ajax request to be completed before valida ...

Is there a way to set up my node package to automatically load sources without having to specifically mention the src directory?

My Node package is structured as follows: ./my-package ./src ./index.js ./a.js ./b.js README.md package.json The package.json file specifies "main": "./src/index.js" and the module loads correctly. However, to import a specific JavaScri ...

What causes the Object expected error in jQuery?

Looking for a way to demo horizontal collapse pane with a simple web page that includes html, css, and jquery. <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <title>Sa ...

jQuery's capability to select multiple elements simultaneously appears to be malfunctioning

I am dynamically creating div elements with unique ids and adding span elements with specific CSS properties. $(".main").append("<div class=largeBox id=" + counter + "</div>"); $(".largeBox").append("<span class=mainTitle></span>"); ...

Exploring Password Verification Techniques in JavaScript

I'm struggling with a password comparison issue in JavaScript. It was working fine on my previous project, but for some reason it's not working now. Here is the HTML code: <form> <label> <strong>Username</ ...

Reading a JSON file stored within the project directory on iPhone PhoneGap using JavaScript

I need to access a JSON file stored in a project folder. Currently, I am using the following code: var obj = "www/places.json"; Can someone help me figure out how to read a JSON file located in the project folder www when working with iPhone PhoneGap an ...

I recently developed a T3 stack project and am currently attempting to configure a next JS middleware, however, I am encountering issues with it not triggering as expected

Having issues with my T3 stack app where the next js middleware is not triggering. I've placed a middelware.ts file in the root directory. middleware.ts // middleware.ts import { NextResponse } from "next/server"; import type { NextRequest ...

How can you include a backslash in data when using AJAX?

Is it possible to send PHP code via AJAX in order to save it in a file? I'm encountering an issue where backslashes are disappearing when trying to send the following code: ...$buffer = "if(\$_POST){".chr(13).chr(10);... Below is the code snipp ...

"Utilize an HTML file open dialog box to gain access to the server's

Is it feasible to implement a file open dialog box that displays files and directories from the server's file system? In my web application, there is a need for users to select a file that resides on the server. Are there any plugins available for th ...

Modify a variety of CSS styles based on boolean values

I am currently working on a web page that needs to adapt based on the local time of the user. Depending on whether it's morning, afternoon, or evening, I want the background image and color scheme to change accordingly. I have made some progress using ...

Unable to transfer data from S3 using piping in a node.js environment

I'm attempting to fetch a file from AWS S3 and stream it to the Express response. Here is my current code: async getMedia(key) { const data = await s3.getObject( { Bucket: process.env.AWS_BUCKET_NAME, Key: key, }, ...

Looking to handle a .csv file containing both quotes and commas within the quotes in Node.js - how can I achieve this

My code solution successfully parses a CSV file, but it doesn't handle cases where data has commas within quoted fields. For example, "not, accounted","normal". let filePath = Path.resolve(__dirname, `./MyData.csv`); let data = fs.readFileSyn ...