A Vue JS Ajax Form is a form that uses Ajax to submit data to a server without reloading the page. This makes the form submission process more efficient and responsive, as users do not have to wait for the entire page to reload. Additionally, Ajax forms can be used to provide real-time feedback to users, such as displaying error messages or updating progress bars.
This tutorial will guide you step by step on how to use ajax request with forms in vue js app. And you can easily pass form data with ajax post request in vue.js. Just follow the following steps and learn how to get checked checkbox value in vue js app with v-model:
In this step, open your terminal and execute the following command to create new vue js app:
vue create my-app
In this step, open your terminal and execute the following commands to install vue axios in your vue js app:
cd my-app
npm install --save axios vue-axios
In this step, visit /src/components directory and create a new component called HelloWorld.vue and add the following code into it:
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Vue Axios Post Example</div>
<div class="card-body">
<form @submit="formSubmit">
<strong>Name:</strong>
<input type="text" class="form-control" v-model="name">
<strong>Description:</strong>
<textarea class="form-control" v-model="description"></textarea>
<button class="btn btn-success">Submit</button>
</form>
<strong>Output:</strong>
<pre>
{{output}}
</pre>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
name: '',
description: '',
output: ''
};
},
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://localhost:8000/your-post-api', {
name: this.name,
description: this.description
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
}
}
</script>
In this step, visit /src/ directory and main.js file. And then add the following code into it:
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
In this tutorial, you have learned how to use ajax with forms in Vue js app.
#vue #ajax