[Javascript] Ajax submission of a Symfony form with Vue-resource and a FormData object

Published on 2019-04-23 • Modified on 2019-04-23

Sometimes, we need to submit a form with Ajax manually. To do so you need to get all the fields' values composing the form and to do a manual submission as if a user had clicked the submit button. Here is the most easiest way I found using the vue.js resource component and a JavaScript FormData object. The main pro is that it avoids building the data manually or doing useless loops.


<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
<script>
    // Just the once will not hurt: This JavaScript snippet is not unit tested for now, but you've got the spirit!
    let vue = new Vue({
        delimiters: ['{', '}'],
        el: '#vue',
        data: {
            form: 'my-form',
            url: '{{ path('homepage') }}',
        },
        methods: {
            subscribeOnClick: function(e) {
                // @see https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
                let form = document.getElementById(this.form);
                let formData = new FormData(form);

                // This example doesn't handle the submission response, it wasn't necessary in my case.
                // @see https://github.com/pagekit/vue-resource/blob/master/docs/recipes.md#forms
                this.$http.post(this.url, formData);

                // That's it! 😁
            }
        }
    });
</script>

 More on Stackoverflow