Laravel. AJAX does not work on apache - ajax

When I run this code by php artisan server it looks good but when I want use apache there is 404 response. But from beginning. Below are the fragments of the code:
Ajax:
$('.item_traveler').select2({
placeholder: 'Wpisz nazwisko podróżnego',
language: "pt-PL",
"language": {
"noResults": function(){
return "Nie znaleziono podróżnego";
},
"searching": function(){
return "Szukam w bazie podróżnych...";
}
},
ajax: {
url: '/autocomplete-ajax-traveler',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.lastname+" "+ item.firstname+" | "+item.email+" | "+ item.city+", ul."+ item.address_street,
id: item.id
}
})
};
},
cache: true
}
});
Routing:
Route::get('/autocomplete-ajax-traveler', 'AutocompleteController#dataAjax_traveler');
Controller:
public function dataAjax_traveler(Request $request)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = DB::table("travelers")
->select("id","lastname","firstname","email","city","address_street")
->where('lastname','LIKE',"%$search%")
->get();
}
return response()->json($data);
}
When I use php artisan serve it looks like:
When I use apache it looks like:
And my .htaccess file contains:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
I'm working on it for 5 days without a result. Please help

on apache,
You have to give full path.
ie.
url: localhost/{Project folder name}/public/autocomplete-ajax-traveler
This way the request will reach your application.

Related

laravel backend page not found

This is vuejs and laravel project. I am facing issue in backend when I type complete url with admin then it says not found. This is happening because I was getting 404 laravel error in refresh inside components. So I used the below route in web.php
Route::get('/{any?}', function () {
return view('index');
});
In Vuejs, I am using the following:
I am using webhistory in route
I am also using fallback route
{
path: "/:pathMatch(.*)",
name: "NotFound",
component: NotFound,
},
backend is based on laravel. Here is the .htaccess data
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
laravel route
I tried the below one:
Route::get('/{any?}', function () {
return view('index');
});
and this one also
Route::get('/{any}', function(){
return view('index');//pointing to the index file of the frontend
})->where('any', '.*');
Route::get('/admin',[AdminAuthController::class,'Create'])->name('create.login');
Route::post('/admin/login',[AdminAuthController::class,'Store'])->name('store.login');
Please suggest

Vue and Laravel SPA routes with params showing blank page on browser refresh and vue is not mounted on #app

I am using vue-router and Laravel for my applcation.
I have a url: http://mywebapp.com/post/{id}
It works when i navigate normally by clicking the above link and vue router loads the component post.vue with route id as route parameter.
But when i refresh the page everything goes blank and vue is not mounted on
<div id="app"></div>
I don't think this is a server configuration issue because my .htaccess file is correctly configured and i don't get a 404 response.
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
it just shows a blank page with no errors on the console so it's hard to trace the problem
The route
{
path: "/post/:id",
name: "Post",
component: Post,
meta: {
requiresAuth: false
}
}
The component
import Post from "./components/post/Post.vue";
when the component is loaded, it makes an Api request to fetch the post using the ID passed from the route
created() {
this.loading = true;
let url = `/post/${this.$route.params.id}`;
axios.get(url).then(response => {
this.loading = false;
this.post = response.data.post;
});
}
Route on api.php
Route::get('/post/{id}', 'PostsController#show');
Controller
public function show(Request $request, $id)
{
$post= Post::find($id);
return response()->json([
'post' => $clip
]);
}
The above codes works normally as expected when i navigate to a post but i just got a blank screen when i reload the browser with no errors reported on the console.
How do i fix this?
Your web.php find should contain a route that matches all routes:
Route::get('/{any}', 'SpaController#index')->where('any', '.*');
This way Laravel doesn't interfere with vue router links.

Laravel 5.1 dont receive JWT token from Dingo API

I use Laravel 5.1 + Dingo API + JWT token. My route is:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function($api) {
$api->post('authenticate', 'App\Http\Controllers\AuthenticateController#authenticate');
$api->post('logout', 'App\Http\Controllers\AuthenticateController#logout');
$api->get('token', 'App\Http\Controllers\AuthenticateController#getToken');
$api->get('test', 'App\Http\Controllers\BitemsController#test');
});
$api->version('v1', ['middleware' => 'api.auth'], function ($api) {
$api->get('authenticated_user', 'App\Http\Controllers\AuthenticateController#authenticatedUser');
$api->get('getvoucher', 'App\Http\Controllers\BitemsController#index');
$api->post('/store', 'App\Http\Controllers\BitemsController#store');
$api->put('/update/{key}', 'App\Http\Controllers\BitemsController#update');
});
Now when I run at Postman to get token everything is fine, so I get:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMDIsImlzcyI6Imh0dHBzOi8vYXBwLmRpbmVhbmRnaWZ0LmNvbS9hcGkvYXV0aGVudGljYXRlIiwiaWF0IjoxNTIwMjAxMzYwLCJleHAiOjE1MjAyMDQ5NjAsIm5iZiI6MTUyMDIwMTM2MCwianRpIjoiNlhTZWdPRllpaGZNWk5sSSJ9.f71ReEY_3I2-uj-7PJNBxbHhO8C50XP5kbShrnmZ8Ig"
}
but now I want to retrieve auth user and I have function protected by middleware, but I get:
{
"message": "Failed to authenticate because of bad credentials or an invalid authorization header.",
"status_code": 401,
"debug": {
"line": 113,
"file": "/home/dgadmin/public_html/test/vendor/dingo/api/src/Auth/Auth.php",
"class": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException", ... ETC...
What is a problem here and how to solve this issue?
Interesting when I make the call like :
https://app.example.com/api/authenticated_user?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMDIsImlzcyI6Imh0dHBzOi8vYXBwLmRpbmVhbmRnaWZ0LmNvbS9hcGkvYXV0aGVudGljYXRlIiwiaWF0IjoxNTIwMjAxMzYwLCJleHAiOjE1MjAyMDQ5NjAsIm5iZiI6MTUyMDIwMTM2MCwianRpIjoiNlhTZWdPRllpaGZNWk5sSSJ9.f71ReEY_3I2-uj-7PJNBxbHhO8C50XP5kbShrnmZ8Ig
then everything is fine... but when I send token as Authorization header with Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMDIsImlzcyI6Imh0dHBzOi8vYXBwLmRpbmVhbmRnaWZ0LmNvbS9hcGkvYXV0aGVudGljYXRlIiwiaWF0IjoxNTIwMjAxMzYwLCJleHAiOjE1MjAyMDQ5NjAsIm5iZiI6MTUyMDIwMTM2MCwianRpIjoiNlhTZWdPRllpaGZNWk5sSSJ9.f71ReEY_3I2-uj-7PJNBxbHhO8C50XP5kbShrnmZ8Ig then I got the 401 error from above...
Why Laravel won't accept authorization header with my token?
I try to add .htaccess file:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^ - [E=HTTPS_AUTHORIZATION:%{HTTPS:Authorization}]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
as you can see I add RewriteRule ^ - [E=HTTPS_AUTHORIZATION:%{HTTPS:Authorization}]
but nothing happened
How to solve this?
You should have an AuthController like so;
use Dingo\Api\Routing\Helpers;
class AuthController extends Controller
{
use Helpers;
/**
* Get the authenticated User.
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
}
In your routes -
api.php, you can have route like this:
$api->version('v1', ['middleware' => 'api.auth'], function ($api) {
$api->post('auth/me', 'App\Http\Controllers\AuthController#me');
});
This returns authenticated user's object. Hope this helps.

Laravel routing page not fount error while passing veriable

I am new to the Laravel while I reading the documentation I had a problem under routing.. it shows we can pass verifiable like this,
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
here what is the user is it Controller or veritable name. I tried to pass the verbal like below but it is getting error
my route code is ,
Route::get('/{id}', function ($id) {
echo 'ID: '.$id;
});
Your route is correct
Route::get('/{id}', function ($id) {
echo 'ID: '.$id;
});
i have tested it and its working fine
Can you check .htaccess file under public folder.
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
Also make sure about laravel project folder name is spelled correctly
As you can see in the url field you trying to get to public/32 and you should try to request such a url:
http://localhost/blog-laravel/public/user/32

500 internal server error with Ajax and .htaccess

i have problem with an ajax.
When i execute my ajax call the response of the page is "500 internal server error".
I suppose is a problem derivated from .htaccess.
This is my code:
Ajax code:
$.ajax({
method: 'POST',
url: "/php/function_ajax.php",
data: "action=doSomething",
success: function(result){
alerrt('Yep, it\'s work!');
},
error: function(request, status, error){
alert(error+' - '+status+' - '+request);
return false;
}
});
This is my .htaccess
ErrorDocument 404 /page-not-found
Options +FollowSymLinks
RewriteBase /
RewriteEngine On
RewriteRule ^font - [L,NC]
RewriteRule ^images - [L,NC]
RewriteRule ^js - [L,NC]
RewriteRule ^php - [L,NC]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request is not for a valid link
RewriteCond %{REQUEST_FILENAME} !-l
and then the rewrite condition for my htaccess.
If i remove the condition "RewriteRule ^php - [L,NC]" it will return "page-not-found".
Someone can help me? Thanks.
alerrt('Yep, it\'s work!');
two r's in alert might be your problem

Resources