I have a multi applicant form in my web app that has a radio button selector section. I managed to get the radio buttons fixed in every new application form but now have a problem in posting the data to PHP and MySQL database. My question is how do I go about posting an array of object to PHP and save it to MySQL database using axios?
I tried to find tutorials on the topic or even finding other questions asked but I didn't find an answer.
let app = new Vue({ el: "#app", data: { buttons: [{ val: null }] }, methods: { addNewRadios(evt) { evt.preventDefault(); this.buttons.push({ val: null }); //console.debug(this.buttons); }, onSubmit(evt) { evt.preventDefault(); const formData = app.toFormData(app.buttons); console.log(formData); //What to do here??? }, toFormData(obj) { let formData = new FormData(); for (var key in obj) { formData.append(key, obj[key]); } return formData; } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <h1>Multiple radio buttons VueJS</h1> <div id="app"> <div class="radio"> <form @submit='onSubmit' method="post"> <div v-for="(button, index) in buttons"> <b>Index {{ index }}:</b> <label:for="'rButton-' + index">option 1</label> <input type="radio":name="'rButton-' + index" value="value-1" v-model="button.val"> <label:for="'rButton-' + index">option 2</label> <input type="radio":name="'rButton-' + index" value="value-2" v-model="button.val"> </div> <br> <button @click="addNewRadios">Add radios</button> <button type="submit">Submit</button> </form> </div> <div> </div> </div>
Here, I have made a few modifications to your code. Build the form data with button values and then post the data using axios,
let app = new Vue({
el: "#app",
data: {
buttons: [{
val: null
}]
},
methods: {
addNewRadios(evt) {
evt.preventDefault();
this.buttons.push({
val: null
});
//console.debug(this.buttons);
},
onSubmit(evt) {
evt.preventDefault();
const formData = app.toFormData(app.buttons);
// What to do here???
// post data to your backend server.
axios({
method: 'post',
url: 'http://example.com/my-url',
data: formData,
}).then(response => {
console.log('Response:', response);
// upon successful post request, you will see the response from the backend server here.
}).catch(err => {
console.log('Error:', err);
// and in case of any error at the backend server.
});
},
toFormData(obj) {
let formData = new FormData();
for (let key in obj) {
formData.append(key, obj[key].val); // appending the button `val` property here, instead of the entire object.
}
return formData;
}
}
});
Then in the backend server, handle the post data. You should receive there an array of the button values that you'd sent.
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.