Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sunrise's avatar

How to append a form's data to formData in vue.js ?

How to append a form's data to formData in vue.js ?

For example:

There is a form,preparing to submit via vue-resource.

html:


<form>
    <span>Message is: {{ message }}</span>
    <br>
    <input type="text" id="message" name="message" v-model="message" placeholder="">

    <button type="submit" class="btn btn-primary" @click="submit">Submit</button>
</form>


vue.js code:

        new Vue({

            el: 'body',
            methods: {
              
                submit: function(e) {
                    e.preventDefault();
                    var data = new FormData();
                    
                    //How to write this sentence below?The value  below is the `input id="message"`'s value.
                    data.append('message', '');
                    

                    this.$http.post('/someUrl', formData).then((response) => {
                        // success callback
                    }, (response) => {
                        // error callback
                    });

                }
            }

        });

The question is in vue.js code above.

0 likes
1 reply
Corben's avatar

A solution would be to prevent the default submit action in the form-tag and let vue handle the submit event, give the form an id and grab the formular data. In this way, you don't even need to extract the data from the text input or use v-model. E.g. like this:

html:

<form id="form" @submit.prevent="submit">
    <span>Message is: {{ message }}</span>
    <br>
    <input type="text" id="message" name="message" placeholder="">

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

vue js:

new Vue({

    el: 'body',
    methods: {
      
        submit: function(e) {
            var form = document.getElementById('form');
            var formData = new FormData(form);
            
            axios.post('/someUrl', formData)
            .then((response) => {
                // success callback
            }, (response) => {
                // error callback
            });
        }
    }
});

I would even create a seperate vue component and put the javascript code there, and use the formular as inline template. In the VueJS code you can of course append more data to the formData before sending.

There are other ways of course.

1 like

Please or to participate in this conversation.