[Vuejs]-Prevent form from submitting with vue.js and axios

0đź‘Ť

âś…

You are using @:submit.prevent="onSubmit" correctly, just remove the form action and handle everything in your onSubmit function.

PD. you likely also need to send info to your axios.post (the form data) currently you are only making an empty POST

0đź‘Ť

I don’t know anything about Vue or Axious, but in general…
Instead of using button with a type of “submit”, set the type to “button”, thus… <button type=\"button\" ... /> This will allow the button to be detached from form submission.

0đź‘Ť

To make things simpler, add an id to that form, say:

echo"
<form id="favoriteForm" method=\"POST\" @submit.prevent=\"onSubmit\" action=\"/validarfavorite.php\" style=\"display:inline-block\">
<div id=\"app\">";

And then you can get the FormData from the <form> and submit it using 'Content-Type': 'multipart/form-data':

new Vue({
  el: '#app',
  data: {
    show: true
  },
  methods: {
    onSubmit: function() {
      axios({
          method: 'post',
          url: '/validarfavorite.php',
          data: new FormData(document.getElementById("favoriteForm")),
          config: {
            headers: {'Content-Type': 'multipart/form-data'}
          }
      })
      .then(function(response) { console.log('success', response); })
      .catch(function(response) { console.log('error', response); });
    }
  }
});

Leave a comment