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')
}
},
storage/logs/laravel.log
). I would imagine there is already a fair amount in there so you might be better off deleting the file, and trying your request again, and then you should have more information on your error. Alternatively, if you go to the preview tab in your console then error should be in there as well. – Ross Wilson Dec 30 '16 at 23:24