haakym
3194
21
General

Submitting form in Vue.js with ajax

Posted 3 years ago by haakym

Hey everyone.

I'm trying really hard to switch over to Vue.js and I'm really stuck on how I would work with submitting a form that makes an ajax request using Vue.js and vue-resource, then using the response to fill a div. I do this from project to project with js/jQuery like this:

view in blade

{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
    <div class="form-group">
        <input type="text" name="id" class="form-control" placeholder="id" required="required">
    </div>
    <button type="submit" class="btn btn-default">Search</button>
{!! Form::close() !!}

js/jquery

var $searchForm = $('#searchForm');
var $searchResult = $('#searchResult');

$searchForm.submit(function(e) {
    e.preventDefault() ;

    $.get(
        $searchForm.attr('action'),
        $searchForm.serialize(),
        function(data) {
            $searchResult.html(data['status']);
        }
    );
});

What I've done/tried so far in Vue.js:

view in blade

{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
    <div class="form-group">
        <input type="text" name="id" class="form-control" placeholder="id" required="required">
    </div>
    <button type="submit" class="btn btn-default" v-on="click: search">Search</button>
{!! Form::close() !!}

vue/js

    Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');

    new Vue({
        el: '#someId',

        data: {

        },

        methods: {
            search: function(e) {
                e.preventDefault();

                var req = this.$http.get(
                    // ???, // url, usually use the form action attribute here
                    // ???, // data, usually use form data here
                    function (data, status, request) {
                        // no idea how I append data to a div using vue.js? 
                    }
                );
            }
        }
    });

I'm wondering if it's possible to use components when dealing with the response to output the response data to a div?

Just to summarise everything:

  1. How do I submit a form using vue js and vue-resource instead of my usual jQuery way?
  2. Using a response from ajax, how can I output data into a div preferably using components?

Any help on this would be most appreciated, thanks.

Please sign in or create an account to participate in this conversation.