I can do what I want! I tried all the 1000 hints I found, but nothing worked. I always get "Internal Server Error". That what I want is to call the MyController@myurl
My 1000th question why I got "Internal Server Error" is:
routes.php:
Route::post( '/myurl', [
'uses' => 'MyController@myurl',
'as' => 'myurl',
] );
my.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>var url = "{{ URL::to('/myurl') }}";</script>
<script>
$( document ).ready( function () {
callmyfunc();
function callmyfunc() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax( {
method: 'POST',
url: url,
dataType: "json",
success: function ( feedback ) {
}
} );
}
} );
</script>
Once sent the token is no longer valid. I just wanted the page to be loaded silently by ajax every 10 seconds. So I have to regenerate a new token manually with another ajax-function before I call myfunction.
// routes.php
Route::get( '/myurl', [
'uses' => 'MyController@myurl',
'as' => 'myurl',
] );
Route::get('/refresh_csrf', function(){
return csrf_token();
});
<!-- blade -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>var url_toCall = "{{ URL::to('/myurl') }}";</script>
<script>var url_refresh = "{{ URL::to('/refresh_csrf') }}";</script>
<script>
$( document ).ready( function () {
setInterval( refreshToken, 10000 );
setInterval( callMyFunction, 10000 );
setInterval( refreshToken, 10000 );
function callMyFunction() {
$.ajaxSetup( {
headers: {
'X-CSRF-TOKEN': $( 'meta[name="csrf-token"]' ).attr( 'content' )
}
} );
$.ajax( {
method: 'GET',
url: url_toCall,
dataType: "json",
success: function ( feedback ) {
}
} );
}
function refreshToken() {
$.ajaxSetup( {
headers: {
'X-CSRF-TOKEN': $( 'meta[name="csrf-token"]' ).attr( 'content' )
}
} );
$.ajax( {
method: 'GET',
url: url_refresh,
dataType: "json",
success: function ( feedback ) {
$( 'meta[name=csrf-token]' ).remove();
$( 'head' ).append( '<meta name="csrf-token" content="' + feedback + '">' );
}
} );
}
} );
</script>