I am trying to run an Ajax post call through my entire application, it shall update the Navigation. On some pages it works but on others it does not, how can I fix this and make it global so to say.
I am using Laravel as a php Framework.
# Middleware group if user is logged in
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification', 'as' => 'notification.'], function () {
Route::post('number', ['as' => 'number', 'uses' => 'NotificationController@number']);
});
Route::group(['prefix' => 'relation', 'as' => 'relation.'], function () {
Route::get('show/{id}', ['as' => 'show', 'uses' => 'RelationController@show']);
});
});
in my layouts/app.blade.php I include the js file like this
<script src="{{ asset('js/liveUpdater.js') }}"></script>
@yield('javascript')
the liveUpdater ajax function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'number',
type: 'post',
success: function(data) {
$('#number-of-notifications').text(data.unread);
},
error: function(data) {
console.log('error number ' + data.data);
}
});
The Url http://localhost/myApp/public/notification/all returns a success message.
But an url for example like this http://localhost/myApp/public/relation/show/1 Returns an error message:
number /myApp/public/relation/show 405 Method Not Allowed
You are prefixing the route with notification
so your ajax request should point to notification/number
:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'notification/number',
type: 'post',
success: function(data) {
$('#number-of-notifications').text(data.unread);
},
error: function(data) {
console.log('error number ' + data.data);
}
});
Also I think aliasing (in the group) wouldn't help, so I think (for simplicity) you could have:
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('number', 'NotificationController@number']);
});
});
You've to define route path and corresponding controller methods for every url paths like for relation/show and notification/all :
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('show/{show}', 'NotificationController@show']);
Route::post('number', 'NotificationController@number']);
Route::post('all ', 'NotificationController@all']);
});
});
mistake in your request method in ajax. it should be type: "GET", OR in your web.php like Route::post('show/{id}' instead of Route::get('show/{id}'
your request method is not matching that why its throwing 405
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.