Display error messages in Vue.js

Within this component, I have a method that updates an employee. My goal is to display the error message in the view immediately after the "errorMessage" variable is assigned/changed within the "error" callback of the ajax call.

var EmployeeEdit = Vue.extend({
        template: '#employee-edit',
        data: function () {
            return {employee: findEmployee(this.$route.params.employee_id),errorMessage:'as'};
        },
        methods: {
            updateEmployee: function () {
                var employee = this.employee;
                $.ajax({
                    url: "/vue/employee/update",
                    type: "POST",
                    data:{
                        id: employee.id,
                        name: employee.name,
                        profile: employee.profile,
                        age: employee.age
                    },
                    success: function (data) {
                        router.push('/');
                    },
                    error:function (xhr, status, error) {
                        console.log("message....... " + xhr.responseText);
                        this.errorMessage =  xhr.responseText;
                    }
                });

            }
    

View:

<template id="employee-edit">

        <section>
            <header class="page-header">
                <div class="row">
                    <div class="col-sm-4">
                        <h1>Edit Employee</h1>
                    </div>
                </div>
            </header>
            <p >{{ errorMessage }}</p>
            <form v-on:submit="updateEmployee">
                <div class="form-group">
                    <label for="edit-name">Name</label>
                    <input class="form-control" id="edit-name" v-model="employee.name" required/>
                </div>
                <div class="form-group">
                    <label for="edit-description">Profile</label>
                    <textarea class="form-control" id="edit-description" rows="3" v-model="employee.profile"></textarea>
                </div>
                <div class="form-group">
                    <label for="edit-price">Age</label>
                    <input type="number" class="form-control" id="edit-price" v-model="employee.age"/>
                </div>
                <button type="submit" class="btn btn-primary">Save</button>
                <router-link to="/" class="btn btn-default">Cancel</router-link>
            </form>
        </section>
    </template>

Answer №1

Due to the loss of the this reference within error:function(){}

You have the option to utilize arrow functions:

error: (xhr, status, error) => {
  console.log("message....... " + xhr.responseText);
  this.errorMessage = xhr.responseText;
}

Alternatively, if you prefer not to use ES6, you can define the context parameter in $.ajax()

$.ajax({
  context: this,
  ...

Or simply retain a reference to this

updateEmployee: function () {
  var _this = this;

...

  error: function (xhr, status, error) {
    console.log("message....... " + xhr.responseText);
    _this.errorMessage =  xhr.responseText;
  }

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

Is it just me or does my node server come preconfigured with CORS enabled? What am I overlooking here?

I have a simple node and express server set up here. Surprisingly, even without any middleware, I am able to successfully log the response from an axios request made to google.com. Doesn't this usually trigger a cors error, requiring some form of midd ...

Implementing optimistic updates with React-query mutations

Hello everyone! I'm a newcomer to react-query and I've been experimenting with making an optimistic update using the mutation function. However, I've encountered a problem where I'm unable to retrieve the previous value from the query. ...

How to deactivate the mobile hardware back button functionality in Ionic 2

Our team has been developing a business application and we've encountered a perplexing issue. Every time we press the mobile hardware back button, our application's GUI becomes disrupted. Despite dedicating numerous hours to finding a solution, t ...

Tips for retrieving the 'Created' value in vue.js

I am currently trying to fetch API JSON data for a weather widget, but unfortunately it is returning null. While I am able to retrieve the JSON data successfully, I am struggling to handle this value. Below is my HTML code snippet: <html> <head& ...

Problem with JWT authentication causing SockJS handshake to block WebSocket connection attempts

I have an operational Spring Boot server with Authentication/Authorization features. However, I am facing issues when trying to establish a connection with SockJS due to my security protocols blocking it. Although I do not have a complete understanding of ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

What is the best way to determine the total of values from user-input fields that are created dynamically

Scenario- A scenario where a parent component is able to create and delete input fields (child components) within an app by clicking buttons. The value of each input field is captured using v-model. Issue- The problem arises when a new input field is crea ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

Vue 3 template refs doesn't quite mirror the true state of the DOM

I'm working on a website to help users plan study schedules. Currently, I'm developing an Add/Remove subject section which allows users to add, edit, or remove subjects with an id and name. The subjects added will be displayed as a list of <i ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

Adding up the values of an array based on their position in Javascript

I came across a JavaScript array that looks like this: var array1 = [ [1, 2, 3], [7, 9, 2], [6, 8, 1] ] What I'm aiming for is to get the following output: var array2 = [ 14, 19, 6 ] array1[0] = 1 + 7 + 6 array1[1] = 2 + 9 + 8 array1[2] = 3 + 2 + ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

Issue encountered while retrieving JSON data from Github

I am currently using d3.json to retrieve a JSON link from the Enterprise GitHub (within the same repository/folder as the JavaScript file). d3.json("https://raw.github.exampleEnterprise.com/path/to/repo/data.json?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Global Redirect Pro is a cutting-edge redirection tool that

Check out the code below which successfully edits a link to redirect users to a specific website based on their location. I'm interested in enhancing this code in two ways: $(window).load(function () { $.getJSON('http://api.wipmania.com/json ...

The 'Bfrip' button is missing from the DOM

Having some issues with displaying table content using DataTables. Everything seems to be working smoothly except for the Buttons, which are not appearing as expected. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.1 ...

Using VueJS to dynamically add a CSS class if a certain filter is

Can you apply this filter rule in VueJS? If an element has the filter discount, the parent will be styled with the class color-green (in this case, the span tag) Check out my JSFIDDLE for more details :) HTML <div id="app"> <h3>50% Disc ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...