Remove a specific date entry from the database using VUE JS and Axios

I am encountering a challenge with Vuejs as I work on a To-Do list. The tasks need to be stored in a MySQL database, and I also want the ability to delete tasks. While I have succeeded in importing and creating data, I'm facing difficulty in deleting data. I've spent a considerable amount of time trying to resolve this issue without success. Can someone provide me with assistance?

APP.js

    var Todo = new Vue({
  el: ".container",
  data() {
    return {
      tasks: [],
      taskText: "",
      errorMessage: "",
      successMessage: "",
      notice: "",
      selectTask: { tasko: "", taskcontent: "" },
      
    }
  },
  computed: {
    validateLengthLetter(){
      if(this.selectTask.tasko.length>65)
      return "Is too long"
    }
  },
    validateLengthLetterButton(){
      if(this.selectTask.tasko.length>65)
      this.$refs.taskan.style.color="red"
    },
  mounted () { 
    this.readTasks();
  },
  methods: {
    completeTask(event){
      event.target.classList.toggle("completed");
   },
    readTasks() { 
      axios
        .get("http://localhost/WhattoDOliste_VUE/db.php?action=read")
        .then((data) => {
          console.log(data.data);
          
          this.tasks = data.data.tasken;
        });
    },
    createTask() {
      let formData = this.convertToFormData(this.selectTask);
      axios
        .post(
          "http://localhost/WhattoDOliste_VUE/db.php?action=create",
          formData
        )
        .then((data) => {});
       //Clearing V-model
       this.selectTask.tasko=""
       this.selectTask.taskcontent="";
       setTimeout(this.readTaskss,3)

    },
    deleteTask(id) {
      let formData = this.convertToFormData(this.id);
      axios
        .post(
          "http://localhost/WhattoDOliste_VUE/db.php?action=delete",
          formData
        )
        .then(function (response) {
          this.selectTask = { tasko: "", taskcontent: "" };
        });

    },

    convertToFormData(data) {
      let fd = new FormData();
      for (value in data) {
        fd.append(value, data[value]);
      }
      return fd;
    },
     
  },
});

db.php

    <?php

//source: https://www.php.net/manual/de/mysqli.construct.php
$conn=new mysqli("localhost", "root", "", "todoliste");
//source https://www.php.net/manual/de/mysqli.connect-error.php
if($conn->connect_error){
    error_log('Connection error: ' . $conn->connect_error);

}

$result=array("error"=>false);
$action="";
if(isset($_GET["action"])) {
    $action=$_GET["action"];
}


//Read Data 

if($action =="read"){
    $sql=$conn->query("SELECT * FROM tasks");
    $tasks=array();
    while($row=$sql->fetch_assoc()){
        array_push($tasks,$row);
    }
    $result["tasken"]=$tasks;
}


//Create Task

if($action =="create"){
    $tasko=$_POST['tasko'];
    $taskcontent=$_POST['taskcontent'];
    
        $sql=$conn->query("INSERT INTO tasks (tasko,taskcontent)VALUES('$tasko','$taskcontent')");

}


//Update Date

if($action =="update"){
    $id=$_POST["id"];
    $tasko=$_POST["tasko"];
    $taskcontent=$_POST["taskcontent"];

    $sql=$conn->query("UPADATE tasks SET tasko='$tasko',taskcontent='$taskcontent',statue='$statue' WHERE id='$id' ");


}



//Delete Task

if($action =="delete"){
    $id=$_POST['id'];
    $sql=$conn->query("DELETE FROM tasks WHERE id='$id'");


}



$conn->close();
echo(json_encode($result));

?>

index.html

<!DOCTYPE html>
<html>

<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="style.css">
</head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<body>

   <div style="text-align: center;"></div>


   <section>


      <div class="container">

         <!-- LEFT LINKS يمين -->

         <div class="left">
            <a href="index.html">
               <h2>To Do List</h2>
            </a>
            <div class="cover">
               <div class="inputs" v-if="selectTask">
                  <form action="" method="post">
                  <input type="text" id="myInput" placeholder="add Task.." name="tasko" v-model="selectTask.tasko">
                  <textarea name="" id="note" cols="30" rows="5" placeholder="Note"
                  name="taskcontent" v-model="selectTask.taskcontent"></textarea>
               </form>
               <div class="btns">
                  <button @click.prevent="createTask()" ref="taskan" v-if="selectTask.tasko"  > <i class="fa fa-plus"></i>Add Task</button>
               </div>
            </div>
          

      <div v-if="!selectTask.tasko" id="Warning">Please enter a task</div>
      <div v-if="validateLengthLetter" id="Warning">{{validateLengthLetter}}</div>


         </div>

         <!-- RIGHT RECHTS يمين -->
         <div class="right">
            <div class="back">
               <ul id="myUL" v-for="task in tasks" :key="task.id" v-if="task">
                  <li  @click="task.status =!task.status" :key="task.id"> <p> {{task.tasko}}</p>
                     <span class="trash" name="delete"  @click="deleteTask(task.id)"> <i class="fa fa-trash"></i></span>

                     <p v-if="!task.status">  {{task.taskcontent}}   </p>
                  </li>
            </div>

         </div>

      </div>
   </section>




   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
   <script src="app.js"></script>


</body>

</html>

Answer №1

Your delete function appears to be using the incorrect id:

 deleteTasks(id) {
  let formData = this.convertToFormData(this.id);

The id is being fetched from the data() component property.

You can try modifying it like so:

deleteTasks(id) {
    axios
        .post(
         "http://localhost/WhattoDOliste_VUE/db.php?action=delete",
         { 'id': id }
        )
        .then(function (response) {
           this.selectedTask = { task: "", taskContent: "" };
        });
}

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

Infuse the theme into the sx prop of MUI 5

The code snippet above was originally written using MUI v4: const useStyles = makeStyles(theme => ({ toolbarMargin: { ...theme.mixins.toolbar } })) To update this code to MUI v5 and utilize the sx prop, I attempted the following implementation: ...

What is the purpose of using a single pipe character within a Vue.js template handlebar expression?

Here is a sample code snippet: <div> {{ name | capitalize }} </div> I have searched through the documentation for vuejs and handlebars, but couldn't find any relevant information. ...

Updating state from a React mapping component: A step-by-step guide

I am working on an API that needs data filtering and then I want to place the filtered data into a state export default class ModifyPage_Single extends React.Component { constructor(props) { super(props) this.state = {data:[],idd:" ...

Server Error: Experiencing an overload of renders. React has set limits on the number of renders to avoid getting caught in an endless loop

I am currently attempting to develop a basic stopwatch application and encountering the following error message. Despite trying various solutions from similar queries, I have not been able to pinpoint the root cause of this issue or resolve it. Below is t ...

Ways to deactivate a button using CSS

I need to use Javascript to disable a link based on its id. By default, the link is invisible. I will only enable the link when the specific id value comes from the backend. HTML <li id="viewroleId" style="display: none;"> <a href="viewrole" ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

What are the steps to effectively create a cascade of Q promises?

Consider the following scenario as an illustration: I have 3 URLs stored in an array called "urls" The "require" function returns a promise that performs an $http call The code provided is functional, but it doesn't meet my desired outcome since th ...

Doesn't the .stop(true) function completely clear the queue as it should?

My slideshow has a hover function to pause it using .stop(true). Upon mouse exit, it should resume playing from where it left off. However, currently, when I hover over it, the animation stops and then continues until it reaches its target, pausing there a ...

Unusual conduct when employing basic directive for validation messages

Within my code, I have implemented the following directive: App.directive("validateMsgFor", function(){ return{ templateUrl : "view/templates/validateMsgFor.html", restrict: "E", scope: { field : "=" } ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

Determine the SVG arc connecting two given points

My situation involves having coordinates for points X and A, A',... as follows: X [x,y] (starting point) A [a,b], A'[a',b'], etc. (ending points) I also have information about angles XCA, XCA', etc. However, I am struggling t ...

Node.js file successfully establishes a database connection, but script tags fail to do so

Having some trouble connecting to my MongoDB database (or MongoLab server). It works perfectly fine when the code is in the name.js file, but for some reason it fails when placed inside <script> tags within an HTML file. My folder contains only thes ...

Accessing and analyzing a stored procedure in SQL Server through SQL script

Currently, I am limited to using SQL commands in an interface with a SQL Server database. I am trying to access a stored procedure to view its contents. Can anyone tell me the SQL command to open a stored procedure for reading? Much appreciated. ...

**The requested resource does not contain the 'Access-Control-Allow-Origin' header.**

When sending emails from a local server using nodemailer, everything works fine. But when on production, an error is thrown in the console: "No 'Access-Control-Allow-Origin' header is present on the requested resource." The setup includes a nod ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Is it possible to switch the linter in grunt.js to jslint instead?

Is it feasible to switch the linter used by grunt.js from jshint to jslint, considering that I am more accustomed to using jslint over jshint as the default linter? ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

Using Ajax and jQuery to Retrieve the Value of a Single Tag Instead of an Entire Page

Let's say I have a webpage named page.html: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Page</title> </head> <body> <h1>Hello World!!</h1> </body> </html> Now ...

Using Vuetify to display text fields in a single row

Check out this Vue component template (View it on CODEPEN): <div class="some-class"> <v-form > <v-container @click="someMethod()"> <v-row> <v-col cols="3" sm="3" v-for="p in placeholders" ...