Question: Call AJAX with Vue.js and Vue resource in Laravel

Question

Call AJAX with Vue.js and Vue resource in Laravel

Answers 1
Added at 2016-12-31 00:12
Tags
Question

I'm making AJAX request in Laravel with Vue.js and Vue resource.

I have view:

{{Form::open(['method' => 'post', 'class' => 'form-inline', 'id' => 'main-form'])}}
{{Form::text('param1', null, ['id' => 'param1', 'class' => 'form-control'])}}
{{Form::text('param2', null, ['id' => 'param2', 'class' => 'form-control'])}}
<input @click="sendIt($event)" type="submit" value="Check prices" class="btn btn-success btn-theme" />
{{Form::close()}}

I have js:

var Vue = require('vue');
var VueResource = require('vue-resource');
Vue.use(VueResource);
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
const app = new Vue({
el: '#app',
methods: {
sendIt: function (e)
    {
        e.preventDefault();
        var token = $('[name="_token"]').val();
        this.$http.post('/data').then((response) => {
            console.log(response);
        }, (response) => {
            console.log(response);
        });
    }
}

Route:

Route::post('/data', 'MainController@data');

And controller:

public function data() 
{
    $msg = $this->test(); //method that retrieves data from db
    return response()->json(['msg'=> $msg], 200);
}

It gives me post 500 internal server error

In response I have this headers:

Cache-Control
Content-Type
Date
Phpdebugbar-Id
Server
Status
Transfer-Encoding
X-Powered-By

In network in my data site I have response headers without token, request headers with token and I have token in Request Payload.

If I change method to get I have same error but if I change method to get and if I remove from my controller part of code where I retrieve data from db and just pass string to json (example:

$msg = 'test';
return response()->json(['msg'=> $msg], 200);

I have success and I can output test on page.

So I'm not sure if it's some problem with token or something else. I tried and this:

var token = $('[name="_token"]').val();
this.$http.post('/prices', {_token:token})

but nothing. Same error again.

If I add this:

http: {
    headers: {
  X-CSRF-TOKEN: document.querySelector('#token').getAttribute('content')
    }
},

I have syntax error on page load.

If I change to this:

http: {
    headers: {
  Authorization: document.querySelector('#token').getAttribute('content')
    }
}

I got internal server error again.

And this is my token in main view:

<meta name="csrf-token" id="token" content="{{ csrf_token() }}">

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

EDIT:

This part works if I add quotes around x-csrf-token but still I have token mismatch error.

http: {
    headers: {
        'X-CSRF-TOKEN': document.querySelector('#token').getAttribute('content')
    }
},
Answers to

Call AJAX with Vue.js and Vue resource in Laravel

nr: #1 dodano: 2016-12-31 01:12

I could be mistaken but in your example at the top you have:

Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');

However, in your main view file you have:

<meta name="csrf-token" id="token" content="{{ csrf_token() }}">

You should be able to simply change $('meta[name=_token]') to $('meta[name=csrf-token]') (so they match).

Furthermore, the reason you had a syntax error with X-CSRF-TOKEN: ... is because you can't use hyphens in key names unless you wrap them in quotes i.e. 'X-CSRF-TOKEN': ....

Hope this helps!

Source Show
◀ Wstecz