What steps should I take to make my Vue JS delete function operational?

As I work on developing my website, I've encountered some challenges. Being new to coding, I'm struggling with creating a functional delete user button. When I click delete, it redirects me to the delete URL but doesn't remove the entry from my home table or MySQL database. Any advice would be greatly appreciated. Below is the code related to the issue:

Home Page Table;

<template>
  <div class="between:flex bottom:margin-3">
    <div class="center: flex-items">

      <!-- This section contains the template for showing entries in a table -->
      
    </div>
  </div>
  <div id="tableHolderDiv">
    <table class="table table-striped">
    
      <!-- Table headings -->

      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">Location</th>
          <th scope="col">End User</th>
          <th scope="col">Order Number</th>
          <th scope="col">Date</th>
          <th scope="col">Application</th>
          <th scope="col">Service Tech</th>
          <th scope="col">Department</th>
          <th scope="col">Hours</th>
          <th scope="col">Travel Hours</th>
          <th scope="col">Contact Name</th>
          <th scope="col">Reason</th>
        </tr>
      </thead>
      <tbody>

        <!-- Displaying rows of data and each row has a delete button -->

        <tr v-for="row in serviceEntries" :key="row.id" @click="alertID(row.id)">
          <td scope="row">{{ row.id }}</td>
          <td>{{ row.location }}</td>
          <td>{{ row.end_user }}</td>
          <td>{{ row.order_number }}</td>

          <!-- Other table cell values -->

          <a href="/delete/{{this.id}}" type="button" class="btn btn-light btn-small" onclick="event.stopPropagation(); return confirm('Are you sure you want to delete this entry?');">
            <i class="bi bi-trash"></i> Delete
          </a>
          
        </tr>
        
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "ServiceTable",
  computed: {
    serviceEntries() {
      return this.$store.state.serviceEntries;
    },
  },
  methods: {
  
    // Method to handle click on a row
    
    alertID(id) {
      this.$router.push({
        path: `/modify/${id}`,
      });
    },
  },
};
</script> 

The only Delete Call; in my app.js

app.delete("/api/service/:id", (req, res) => {
  pool.query(
    "DELETE FROM `master` WHERE id = ?",
    [req.params.id],
    function (error, results, fields) {
      if (error) res.json(error);
      else res.json(results);
    }
  );
});

Do I possibly need to add an app.post for delete?

Answer №1

GET method is being used by the a tag but you require a DELETE request. To achieve this, use a button along with a handler where you can utilize a library like axios or got for making various types of requests such as GET, POST, PUT, and DELETE.

<button
  class="btn btn-light btn-small"
  onclick="onDelete">
  <i class="bi bi-trash"></i>
  Delete
</button>
<script>
import axios from 'axios';

export default {
  methods: {
    async onDelete() {
      if(!confirm('Are you sure you want to delete this entry?') {
        return
      }
      await axios.delete(`/delete/${this.id}`);
    },
    alertID(id) {
      this.$router.push({
        path: `/modify/${id}`,
      });
    },
  },
};
</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

Encountering issues with link button redirection

I have a question regarding a Link element and CustomButton element with an onClick handler. < Link to = "/dashboard" style = { linkStyles } > < CustomButton text = "Login" onClick = { handleSubmit } /> < /Link> The code ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Update the directory path for Angular ui-bootstrap templates

Currently, I am attempting to utilize ui-bootstrap.min.js in conjunction with external templates. An issue has arisen where the error message reads as follows: http://localhost:13132/Place/template/timepicker/timepicker.html 404 (Not Found) I desire fo ...

Using jQuery to close a DIV with a delay

At the top of my website, I have set up an alert with a close button. The jQuery function for closing the alert is as follows: /* CLOSE ALERT BAR WITH BUTTON */ $('a.ctp-alert').click(function () { $("div.ctp-alert").slideUp(); }); While this f ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with: $scope.Background = 'img/seg5en.png'; document.getElementById("Bstyle").style.background = "url("+$scope.B ...

Is there a way to create a footer similar to this one?

I need to create a footer, but I'm struggling with placing a circle at the top half of the footer like this. Even though I can create a footer, I still encounter some issues. This is the code I have right now: .Footer { position: fixed; left: ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Combining 2 rows in an HTML table: A step-by-step guide

Can anyone help me figure out how to merge the first row and second row of a table in HTML? I have already merged two rows, but I am having trouble merging the first and second rows together. This is how I want my rows to be merged: |-------------------- ...

The depth order of overlapping elements and the rotation effect achieved through

I have created some interactive flip cards using CSS and HTML with transitions Currently, when you hover over a card, it flips and enlarges. However, I am facing an issue with positioning the hovered card on top using z-index and relative position due to ...

Looking to align a radio button in the middle of an inline-block?

Is it possible to center a radio button within an inline-block? I have provided a demo on JSFiddle that displays the current layout and how I envision it should appear. Check out the demo here Here is the code snippet in question: <span style="widt ...

Pass function A as a prop, then trigger a different function when the child function calls A

Apologies for the uninformative title; I struggled to come up with a suitable one regarding my issue. I have a question concerning React code. My Child component receives the onValueChanged function as a prop. This function was initially passed down to th ...

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

Why is React only displaying an empty screen instead of showing errors like on my instructor's system? How can I resolve this issue? EDIT: While I can see the error in the console and IDE, I want to test error boundaries. When using error boundary a ...

Changing the CSS Border of Thumbnails

Take a look at this screenshot of a thumbnail grid. I need to reposition the gray border so that it sits below the price and is consistently aligned across all products. The challenge arises when product titles vary in length, causing the price to be posit ...

Having trouble extracting a JSON object from a POST request in Express v4 with the help of body-parser?

Currently, I am delving into the world of server-side code and learning about Node.js and Express. However, I am facing some challenges when it comes to receiving and parsing a JSON object sent from a POST request. Despite checking various resources (linke ...

maintaining connections does not store components

I am encountering a problem with the keep-alive functionality not actually keeping components alive. The component that is being rendered in the router-view has asynchronous fetching after the component is mounted. My issue arises when, after the first ti ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

Guide to make a loading animation button through the use of HTML, CSS, and JavaScript

"Hello, I am currently in the process of working on a project and am interested in implementing a button with a loading animation that can be displayed during actions like form submission or content loading. I'm seeking some advice or code sample ...

Seeking assistance with using JavaScript to filter posts from Contentful for a Next.js website

Currently, I am integrating a Next.js blog with Contentful and employing queries to display posts on the homepage. While I can easily use .filter() to feature certain posts based on a boolean value, I am struggling to figure out how to fetch posts that mat ...

Using JSON / jQuery: How to Handle XML Data in the Success Function of an AJAX Post Request

Greetings! I am currently performing an ajax post through a JSP. The JSON data is being sent in string format (parsed using parseJSON, then converted back to a string using JSON stringify). The post operation functions correctly. However, my query lies in ...