mercredi 29 juin 2016

Submit form using VueJs and AJAX in Laravel 5.1

I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.

The blade file:

<body>
    <div class="container">
        <generate-admin></generate-admin>
    </div>

    <script src="https:http://ift.tt/IJSC3o"></script>
    <script src=""></script>
</body>

The component:

<template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default {
        data: function() {
            return {
                username: ''
            }
        },

        methods: {
            createAdministrator: function() {
                formContents = jQuery("#createAdministrator").serialize();

                this.$http.post('/admin', formContents).then(function(response, status, request) {
                    console.log(response);
                }, function() {
                    console.log('failed');
                });
            }
        }
    }
</script>

main.js

import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';

var VueResource = require('vue-resource')
Vue.use(VueResource);

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

new Vue({
    el: 'body',

    components: { GenerateAdmin }
});

gulpfile.js

var elixir = require('laravel-elixir');

require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
});

routes.php

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function(Request $request) {
    // returns an empty object.
    return response(['results' => $request]);
});

Route::get('/', function () {
    return view('welcome');
});

What I get in return is:

"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"

When I check the Request Payload section of Network Tab in Chrome.. I do see that the form is getting submitted successfully with whatever data I write in the text box above.

Why is this happening ? Kindly guide me where I have made the mistake ?

P.S.: I have started learning VueJs Components recently.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire