How to submit form in Vue.js with Ajax and JavaScript?

Sometimes, we want to submit form in Vue.js with Ajax and JavaScript.

In this article, we’ll look at how to submit form in Vue.js with Ajax and JavaScript.

How to submit form in Vue.js with Ajax and JavaScript?

To submit form in Vue.js with Ajax and JavaScript, we can create a FormData instance from the form values.

For instance, we write

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

<div id='app'>

</div>

to add the Vue script and the app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div>
      <form @submit.prevent='submit'>
        <input name='title'>
        <input name='content'>
        <input type='submit'>
      </form>
    </div>
  `,
  methods: {
    async submit(e) {
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: new FormData(e.target),
      })
    }
  }
})

to add a form.

We set the @submit.prevent directive to submit run submit when we click Submit.

In submit, we create a FormData instance by passing e.target into it, where e.target is the form element.

As a result, when we click Submit, the form values with the name attribute values as the keys and the input values as their corresponding values will be submitted.

Conclusion

To submit form in Vue.js with Ajax and JavaScript, we can create a FormData instance from the form values.