Insert the latest information into the table following the completion of the form in VueJS

When making a POST request to submit data using an endpoint, such as http://localhost:3000/entry, with keys like fname, lname, and age, the submission is successful. However, I am facing an issue where upon form submission, it redirects to the endpoint itself instead of staying on the current page. My project is built using VueJS.

In addition, there is another endpoint available at http://localhost:3000/entries (GET) which returns existing entries in JSON format, for example:

[
    {
        "_id": "5b48a137c3b2a3454b853a3c",
        "fname": "John",
        "lname": "Jose",
        "age": "28",
        "__v": 0
    },
    {
        "_id": "5b506cc7d9105012f59c87e6",
        "fname": "Alex",
        "lname": "Cruz",
        "age": "27",
        "__v": 0
    }
]

Instead of redirecting when submitting the form, my goal is to update the HTML table with the latest data from the API endpoint http://localhost:3000/entries.

In the provided code snippets, index.html mentions the necessary scripts and styles for vue.js implementation, along with form elements and a table structure for displaying data. The script.js file includes Vue instance creation with data properties and methods for form validation. Lastly, an updated version of the table structure is given to handle dynamic rendering of entry details fetched from the API endpoint.

Answer №1

In the method checkForm, if anything is typed in the fname-input, it returns before e.preventDefault() is executed. To prevent form navigation, move e.preventDefault() to the beginning of the method.

Additionally, the last name input also utilizes fname as v-model.

To display data in the table, you can use the following approach:

index.html

<table style="width:100%">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
    </tr>
    <tr v-for="(row, index) in table" :key="index">
        <td>{{row.fname}}</td>
        <td>{{row.lname}}</td>
        <td>{{row.age}}</td>
    </tr>
</table>

script.js

data: {
    return {
        ...
        table: []
    }
},
mounted() {
    this.populateTable()
},
methods: {
    checkForm(e) {
        e.preventDefault();
        if (this.fname) {
            table.push({ fname: this.fname, lname: this.lname, age: this.age })
            return true;
        }
        this.errors = [];
        if (!this.fname) this.errors.push("First name required.");
        return false;
    },
    populateTable() {
        /* GET-request, put into this.table */
    }
}

Answer №2

To send data to the server, utilize an ajax request instead of a form action:

  1. In your template, ensure that the form opens like this (without specifying action and method):

    <form class="row" @submit.prevent="checkForm">
    
  2. Implement ajax to transmit data to the server (noting the use of vue-resource):

    checkForm:function(e) {
        this.errors = [];
        if(!this.fname) this.errors.push("First name required.");
        if (this.errors.length) {
           return;
        }
        var data = {
            fname: this.fname,
            lname: this.lname,
            age: this.age
        }
        this.$http.post('http://localhost:3000/entry', data, { emulateJSON: true })
        .then(function(){
            console.log('Saved!');
         });
    }
    
  3. This process ensures automatic updating of data in the table.

UPDATE

Additionally, you require an array of objects to correctly render the table - which I have set up in an example using jsonplaceholder to demonstrate its functionality. Upon saving the form, the app retrieves all objects from the server. Please remember to adjust the URLs for your specific needs in order for everything to work perfectly. Also, ensure to update the output fields in the table with the correct ones - I have added comments to guide you through this process.

. . . // The rest remains unchanged as it is important content from the original text. . .

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 Trigger a Javascript Function from an OnItemClick Event in ASP.NET ListView

In order to achieve the functionality of refreshing ListView No.2 without refreshing the entire page when a user clicks on an item in ListView No.1, I am attempting to use JavaScript. Here is what I have tried so far: ListView No.1: <asp:ListView ID=" ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

`NodeJS Compared to Static HTML`

I need to create a browser client for my Java Rest API and I'm considering the best approach with the least trade-offs. Should I use static HTML files with backbone to connect to the REST API and populate the data fields? Or should I opt for a NodeJ ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...

Seeking out all of the children associated with their parent using Jquery

Currently, I am utilizing Codeigniter and Jquery in conjunction with the AJAX method to retrieve data from two tables within my database by using a select join operation on the 'group' table and 'cat' table. Below is a description of t ...

Create a search feature using Javascript and React that retrieves and displays results from a

I am currently developing a React application with a search feature that fetches JSON data and displays matching search results on the website import { React, useState } from 'react'; export default function PractitionerSearch() { const [data ...

Tips to avoid the page from scrolling to the top when the menu is opened

Whenever a user taps the menu button on the page, a full-page menu opens. However, there is an issue - the main content page automatically scrolls to the top. Can you provide suggestions on how to prevent this from happening? I have already looked into a s ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

When incorporating a background-image into my Vue.js project, I encountered this error

I encountered an issue after adding a background-image to my vue.js project: ./src/assets/scss/argon.scss (./node_modules/css-loader??ref--8-oneOf-3-1!./node_modules/postcss-loader/src??ref--8-oneOf-3-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf ...

Working with Node.js and JavaScript's Date object to retrieve the time prior to a certain number of hours

I am currently working on a script in node.js that is able to locate all files within a specific directory and retrieves their modified time: fs.stat(path, function(err, states){ console.log(states.mtime) }) After running the script, it ...

Prevent the use of harmful language by implementing jQuery or JavaScript

Is there a way for me to filter certain words (such as "sex") using regex, even when people use variations like "b a d", "b.a.d", or "b/a/d"? How can I prevent these kinds of words from getting through? I'm trying to filter more than just one word - ...

What are the distinctions in how jQuery behaves when an element is assigned to a variable versus in Javascript?

I've noticed that when I assign a jQuery element to a variable, it doesn't match the element in a comparison. However, if I assign a JavaScript element, it does... test1 = $(".the_div"); console.log(test1 == $(".the_div")); // This logs false ...

Should tokens be sent via POST request or stored in a cookie?

I have a single-page Node.js Facebook Canvas App. Whenever a user interacts with the app, it triggers an AJAX POST request to my Node.js HTTPS server, which then returns the result. Now, I am looking for a way to send a user token that I generate from the ...

.value not showing correct data in JavaScript

I am attempting to retrieve the value entered by the user in an HTML input field. While I can display a fixed, predetermined value with ease, this is not my intention. My goal is for users to input a numerical value and for that value to be displayed/adj ...

VueJS showcasing information from an API

I'm having an issue with displaying data fetched from an API using Axios. Even though I can see the data when I console.log(app.books), it does not show up on the page as expected. I'm utilizing v-for to populate a table with the data, but someth ...

Contrast between npm run dev and npm run production

As a beginner in Laravel and Vue.js, I'm curious to learn about the distinction between running npm run dev and npm run production. Could someone explain if this is related to the environment? ...

Exploring the Concept of Adding Two Numbers Algorithm

While working on a LeetCode problem, I came across the following scenario: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

Unable to retrieve scroll position utilizing 'window.scrollY' or 'window.pageYOffset'

Issue I am facing a problem where I need to determine the scroll position in order to adjust the tooltip position based on it. This is how my tooltip currently appears: However, when I scroll down, I want the tooltip to toggle downwards instead of its c ...

adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row wa ...