Home » vue » Delete date from database via VUE JS /Axios

Delete date from database via VUE JS /Axios

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a problem with Vuejs, I am currently doing a TO do list and the tasks should be in Mysql database and I also need to have the tasks deleted.
I did it, I can import the data and I can also create data, but I cannot delete the data 🙁 can someone help me, I tried a long time but in vain

APP.js

    var Todo = new Vue({
  el: ".container",
  data() {
    return {
      tasks: [],
      taskText: "",
      erorrMassage: "",
      successMassage: "",
      notitze: "",
      selectTask: { tasko: "", taskcontent: "" },
      
    }
  },
  computed: {
    validatelengthleeter(){
      if(this.selectTask.tasko.length>65)
      return "Ist zu lang"
    }
  },
    validatelengthleeterbutton(){
      if(this.selectTask.tasko.length>65)
      this.$refs.taskan.style.color="red"
    },
  mounted () { 
    this.tasklesen();
  },
  methods: {
    erledigt(event){
      event.target.classList.toggle("erledigt");
   },
    tasklesen() { 
      axios
        .get("http://localhost/WhattoDOliste_VUE/db.php?action=read")
        .then((dieDaten) => {
          console.log(dieDaten.data);
          
          this.tasks = dieDaten.data.tasken;
        });
    },
    taskanlegen() {
      let formData = this.convertToFormData(this.selectTask);
      axios
        .post(
          "http://localhost/WhattoDOliste_VUE/db.php?action=create",
          formData
        )
        .then((dieDaten) => {});
        //V-modell entleeren
       this.selectTask.tasko=""
       this.selectTask.taskcontent="";
       setTimeout(this.tasklesen,3)

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

    },

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

db.php

    <?php

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

}

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


//Daten Lesen قراءة او استدعائ المهام Read Date

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


//Task anelegen   انشاء مهمة Create Task

if($action =="create"){
    $tasko=$_POST['tasko'];
    $taskcontent=$_POST['taskcontent'];
    
    //هون انشاء البيانات
        $sql=$conn->query("INSERT INTO tasks (tasko,taskcontent)VALUES('$tasko','$taskcontent')");

}

//Task bearbeiten   تعديل الواجب  Upadate 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' ");


}



//Task löschen
//   حذف المهمة
// Remove  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="Notiz"
                  name="taskcontent" v-model="selectTask.taskcontent"></textarea>
               </div>
               <div class="btns">
                  <button @click.prevent="taskanlegen()" ref="taskan" v-if="selectTask.tasko"  > <i class="fa fa-plus"></i>Add Task</button>
                  <!-- <button  @click="" > <i class="fa fa-trash" ></i> Delete all</button> -->
                  <!-- <button > <i class="fa fa-file-pdf-o"> </i>Download as PDF </button> -->

               </div>
            </form>
            </div>
          

      <div v-if="!selectTask.tasko" id="Warnung" >Bitte einen Task eintragen</div>
      <div v-if="validatelengthleeter" id="Warnung" >{{validatelengthleeter}}</div>

        <!--
      <a href="#" id="Warnung" v-on:click="showEditModal=true, chooseUser(user)==''" >Bitte einen Task eintragen</a>


               <div id="empfehlung">asdasdasdasd</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="trush" name="delete"  @click="deleteTasks(task.id)"> <i class="fa fa-trash"></i></span>
            <!-- <span class="okay" @click="erledigt"> <i class="fa fa-check"></i> </span> -->

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

         </div>

      </div>
   </section>




   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
   <script src="app.js"></script>


</body>

</html>
Answers:

Your delete method is using wrong id:

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

Which is getting id from data () component property.

Try posting it like this:

deleteTasks(id) {
    axios
        .post(
         "http://localhost/WhattoDOliste_VUE/db.php?action=delete",
         { 'id': id }
        )
        .then(function (respons) {
           this.selectTask = { tasko: "", taskcontent: "" };
        });
}