route not found on ajax post - php

I'm trying to create a dependent select using ajax, here is my JS
$("#make").change(function(){
$.ajax({
url: "{{ url('chauffeur/ajax_vehicle_model') }}?make=" + $(this).val(),
method: 'GET',
success: function(data) {
$('#model').html(data.html);
}
});
});
My routing looks like this
Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('chauffeur/ajax_vehicle_model','Admin\ChauffeurController#get_vehicle_model');
});
And in my controller I have this
public function get_vehicle_model(Request $request)
{
....
}
But I get a 404 error, any idea what I'm doing wrong here?

Try to change your route like this
routing file
Route::get('chauffeur/ajax_vehicle_model', ['as'=> 'chauffeur.ajax.vehicle', 'uses' => 'Admin\ChauffeurController#get_vehicle_model']);
Now your js code should be like this (if your js code is in .blade.php file)
$("#make").change(function(){
$.ajax({
url: "{{ route('chauffeur.ajax.vehicle') }}?make=" + $(this).val(),
method: 'GET',
success: function(data) {
$('#model').html(data.html);
}
});
});
try this.

As you see, you have an argument in your route group prefix, with the value admin.
This prefixes your routes inside that route group with admin. This way, your url in JS should look like:
url(“admin/chauffeur/ajax_vehicle_model”)

Related

Problem with route in Ajax using Laravel?

I am trying to get a list of countries with their cities using Select2 with Jquery.
At the time of creating a post with their respective country and city, I don't have a problem, but at the time of editing the post I miss the following error:
http: //imperial.test/dashboard/posts/40/edit/getStates/6 (Not Found)
D:\laragon\www\Imperial\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php # 179
Routes:
Route::group([
'prefix' => 'dashboard',
'namespace' => 'Admin',
'middleware' => 'auth'],
function(){
Route::get('/', 'AdminController#index')->name('dashboard');
Route::resource('posts', 'PostsController', [
'names' => [
'index' => 'dashboard.posts.index',
'create' => 'dashboard.posts.create',
'store' => 'dashboard.posts.store',
'edit' => 'dashboard.posts.edit',
'update' => 'dashboard.posts.update',
'destroy' => 'dashboard.posts.destroy',
],
]);
Route::get('posts/create/getStates/{id}', 'PostsController#getStates');
Route::get('posts/create/getCities/{id}', 'PostsController#getCities');
Route::get('posts/edit/getStates/{id}', 'PostsController#getStates');
Route::get('posts/edit/getCities/{id}', 'PostsController#getCities');
Route::get('images/posts/{id}/avatar/{image}', [
'uses' => 'PostsController#postProfileAvatar',
]);
});
My Script
$(document).ready(function(){
$('select[name="country_id"]').on('change',function(){
var country_id = $(this).val();
if(country_id)
{
$.ajax({
url: '/edit/getStates/'+country_id,
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
$('select[name="state_id"]').empty();
$.each(data, function(key, value){
$('select[name="state_id"]')
.append('<option value="'+key+'">' + value + '</option>');
});
}
});
} else {
$('select[name="state_id"]').empty();
}
});
$('select[name="state_id"]').on('change',function(){
var state_id = $(this).val();
if(state_id)
{
$.ajax({
url: '/edit/getCities/'+state_id,
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
$('select[name="city_id"]').empty();
$.each(data, function(key, value){
$('select[name="city_id"]').append('<option value="'+key+'">' + value + '</option>');
})
}
});
}else {
$('select[name="city_id"]').empty();
}
});
});
N' in the blade if the script path is registered:
<script src="{{ asset('js/worldedit.js') }}" defer></script>
Any suggestions on how to solve this error, I tried it in a separate project without using Route :: group and prefixes and I did it with GET routes and it worked, so I deduce that the problem is in the ajax route
Your route is under a group with prefix dashboard, so shouldn't it be
url: '/dashboard/posts/edit/getStates/'+ country_id
Instead of just
url: '/edit/getStates/'+country_id
When you are viewing a post your current address is
http: //imperial.test/dashboard/posts/40
and your javascript has this url (relative address)
url: '/edit/getStates/'+country_id,
So ajax call actually get this url:
http: //imperial.test/dashboard/posts/40/edit/getStates/6
While you are defining route (in laravel web.php) for
http: //imperial.test/dashboard/posts/edit/getStates/{id}
So you get not found error.
Define your routes as
Route::get('posts/{postid}/edit/getStates/{id}', 'PostsController#getStates');
Route::get('posts/{postid}/edit/getCities/{id}', 'PostsController#getCities');
You must use the route helper to get the route by name. In this case, you can do the following:
In the html "select" element:
For example, suppose you have a route called "cities.list" that retrieves all cities in this state:
<select name="state_id" data-route="{{ route('cities.list', ['id' => ':id']) }}" >
So, in the js script just use that route as follows:
....
var select_state = $('select[name="state_id"]'); // or $(this)
var route = select_state.data('route')
route = route.replace(':id', select_state.val())
$.ajax({
url: route,
type: 'GET',
dataType: 'json',
....
Did you get the idea?

How to write url in ajax in laravel?

I want to call storeProduct controller method in ajax URL.
url: './product_catalog/storeProduct'
How to call a method in this URL?
I want to store product_id and campaign id in the database.
Page not found error occurs.
Route :
Route::get('product_catalog','front\ProductCatalogController#showProductCatalogForm');
Route::post('product_catalog',['as' => 'storeProduct', 'uses' => 'front\ProductCatalogController#storeProduct']);
Ajax :
$(".my_form").submit(function(event) {
event.preventDefault(); //prevent default action
var product_id = $(this).find('#product_id').val();
var campaign_id = $(this).find('#campaign_id').val();
console.log(product_id);
console.log(campaign_id);
$.ajax({
type: "POST",
url: './product_catalog/storeProduct',
data: {
'product_id': product_id,
'campaign_id': campaign_id
},
success: function(data) {
alert(data);
console.log(data);
}
});
});
Controller :
public function showProductCatalogForm()
{
//if($_GET["campaign"]!=="")
$campaign=$_GET["campaign"];
return view('front.product_catalog');
}
public function storeProduct(Request $request)
{
$this->validate($request, $this->rules);
$input=Input::all();
$campaign_product=ProductCatalog::create($input);
return redirect('product_catalog');
}
url: {{ url('/product_catalog/storeProduct') }},
your route should be
Route::get('/product_catalog','front\ProductCatalogController#showProductCatalogForm');
your ajax url should be
type: "POST",
url: '/product_catalog',
Or you can use route(); i recommend dont use url() because any time if you want change urls you will need to change it manually.which is not good for app.urls could be 100 or 1000 to change.it could be dangers.
you should try name route like this
Route::get('/product_catalog','front\ProductCatalogController#showProductCatalogForm')->name('product_catalog');
and your ajax url
type: "POST",
url: {{ route('product_catalog') }},
Why you are adding "." In ./product-catalog !
Just use /product-catalog
Use "." when you want to search for folder or any directory or any file in your project directory or any other folder and you are not sure where the file is
Dont use in url when there is a route for the link
try this if you have wrote javascript inside blade :
$(".my_form").submit(function(event) {
event.preventDefault(); //prevent default action
var product_id = $(this).find('#product_id').val();
var campaign_id = $(this).find('#campaign_id').val();
console.log(product_id);
console.log(campaign_id);
$.ajax({
type: "POST",
url: '{{route('storeProduct')}}',//this is only changes
data: {
'product_id': product_id,
'campaign_id': campaign_id
},
success: function(data) {
alert(data);
console.log(data);
}
});
});
use this without the dot before slash.
url: '/product_catalog/storeProduct',
You could use
url:"{{route('route.name')}}"
and it works for me. You could check it by
console.log("{{route('route.name')}}");
inside your script.

Laravel AJAX 404 for route

I am working on a Laravel 5.3 solution. I try to call a POST route via AJAX from one of my views to update a set of categories but I get a 404 error everytime I call the route.
Interesting fact: During development I was able to call the route with the JS-code shown below successfully - but since I did some updates to the controller code itself it throws a 404 but no exception.
Here is my controller action:
public function updateTree( Request $request )
{
$data = $request->json()->all();
$result = BlogCategory::rebuildTree($data, false);
if($result > 0) {
return Response::HTTP_OK;
}
return Response::HTTP_NOT_MODIFIED;
}
And here the JS AJAX call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var updateTree = function (e) {
var list = e.length ? e : $(e.target), output = list.data('output');
console.log(JSON.stringify(list.nestable('serialize')));
$.ajax({
url: '{{ action('BlogCategoryController#updateTree') }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
};
$(document).ready(function() {
$('#nestable2').nestable({
group: 1
}).on('change', updateTree);
});
The controller route is bound like that in web.php
Route::post( '/service/blog/categories/updatetree', 'BlogCategoryController#updateTree' );
As you might see, I am using the Laravel NestedSet module from LazyChaser here (https://github.com/lazychaser/laravel-nestedset).
Any input is much appreciated.
Cheers,
Jules
you having opening and closing quotes problem in your ajax url, use like this
$.ajax({
url: '{{ action("BlogCategoryController#updateTree") }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});

Laravel 5.4 Api Route 401

I built a new laravel 5.4 project.
I tried to do the steps below in my api route, but somehow they do not work.
In my app.js file I have this ajax call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'api/postStream',
type: 'post',
data: { imgData: imgData },
success:function(data) {
console.log('success');
}
});
My Api Route looks like this:
Route::group(['middleware' => 'auth:api'], function()
{
Route::post('postStream', ['as' => 'image', 'uses' => 'ApiController#postStream']);
});
And my controller:
public function postStream(Request $request)
{
$imgData = $request->imgData;
...
}
But I get this error in my chrome dev console:
POST http://localhost/app/public/api/postStream 401 (Unauthorized)
And in the network tools this:
{error: "Unauthenticated."}
error
:
"Unauthenticated."
I guess I am somewhat not authentificated, but I do not know how to make that happen this way.
It doesn't work because your route is protected by auth:api, which returns 401 unauthorized. The only way to go through auth:api is to send your authentication token with every single request
var token = <?php json_encode(Auth::user()->api_token); ?>; //if you are using api_token
$.ajax({
url: 'api/postStream',
headers: {
'Authorization':'Bearer ' + token,
},
type: 'post',
...
});
The way you get your token is entirely up to you. You could use Passport or simply the easiest solution which is adding api_token to your users table.
If you are going for the cheapest solution, you can follow this post: https://gistlog.co/JacobBennett/090369fbab0b31130b51

Update with Laravel and ajax

Hello everybody iam new to laravel and i hope you will help me to solve this problem. I want to update a particular column conditions, 1 to 0 and 0 to 1 when user click the link with Ajax.
I have column named status which can have value 1 or 0,according to user click the link value gets updated.
I have two route
Route::get('/logo/updateY/{id}', [ 'uses'=> 'Backend\Logo\LogoController#updateYesStatus', 'permission'=> 'update' ]);
Route::get('/logo/updateN/{id}', [ 'uses'=> 'Backend\Logo\LogoController#updateNoStatus', 'permission'=> 'update' ]);
controller
public function updateYesStatus($id)
{
$logoStatus = Logo::findOrFail($id);
$logoStatus->update(['status'=>'1']);
return redirect::to('administrator/logo/view');
}
public function updateNoStatus($id)
{
$logoStatus = Logo::findOrFail($id);
$logoStatus->update(['status'=>'0']);
return redirect::to('administrator/logo/view');
}
view:
#if($logo->status== 1)
<td >Displayed</td>
#else
<td >Hidden</td>
#endif</td>
<script type="text/javascript">
$(document).on('click','.userStatus',function(){
var id = $(this).attr('id');
$.ajax({
data:{ id=id, _token: '{!! crfs_toekn() !!}'},
url: '',
type: 'POST',
dataType: 'json'
success:function()
{
}
});
});
</script>
1) Use the same method (GET or POST) in the ajax and at routes
2) You should fix the ajax data
{id: id, _token: '{!! csrf_token() !!}'}
3) You should pass the url to ajax

Categories