Problem with route in Ajax using Laravel? - php

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?

Related

Laravel dosent delete record via ajax?

I'm trying to delete record using ajax, in laravel 5.4, I know this is one of the common questions and there are already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me the same error NetworkError: 405 Method Not Allowed. I tried to do this task by different angle but I'm stuck and could not found where I'm wrong, that's why I added this question for guideline.
I'm trying the following script for deleting the record.
IN Route:
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
In Controller:
public function delete_article($id)
{
article::where('id', $id)->delete($id);
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
IN View:
<li name="csrf-token" content="{{ csrf_token() }}">
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
<i class="icon-bin"></i>delete
</a>
</li>
Ajax Code is:
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: /admin/article/delete/{{article}},
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
console.log("it Works");
}
});
});
As you can See it seems everything is right but I don't know why it doesn't work correctly?
please help me, guys.
This is work for me:
In Route
Route::post('/article/delete', 'ArticleController#delete_article');//Ajax Routes
IN Controller
public function delete_article(Request $request)
{
$id=$request['id'];
article::where('id', $id)->delete();
return response()->json(['articleDelete' => 'success']);
}
in View:
<td>
<a class="deleteRecord" data_id="{{$article->id}}">
<i class="icon-bin" style="color: black"></i></a>
</td>
In AJAX:
$(".deleteRecord").each(function () {
$(this).on("click", function () {
var $tr = $(this).closest('tr');
var id = $(this).attr("data_id");
swal({
title: "Are you sure to Delete!",
text: "***",
icon: "warning",
buttons: [
'cansle!',
'yes'
],
dangerMode: true,
}).then(function(isConfirm) {
if (isConfirm) {
$.ajax({
url: '/admin/article/delete',
type: 'post',
dataType: 'json',
data: {_token: "{{csrf_token()}}" , id:id},
success: function () {
swal({
title: "article deleted succesfuly",
icon: "success",
type: 'success',
})
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
});
}
})
}
})
});
});
The problem (as far as I can see) lies here:
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
In your view, you make a variable named id and the value is based on data-id attrribute.
var id = $(this).data("id");
But in your a tag you don't have data-id attribute. So you have to add it (something like this):
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}" data-id="{{$article->id}}">
Also in your ajax call, teh url is incorrect (based on what you have defined in routes:
Ajax call:
url: "article/"+id
Route:
article/delete/{article}
So either change the route:
article/{article}
or change the ajax call:
url: "article/delete/"+id
And one more thing. You have to prevent default a tag action. change the event like this:
$(".deleteRecord").click(function(event){
event.preventDeault();
You are doing wrong in many places. Try this
Route
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
Controller
public function delete_article($article)
{
article::where('id', $article)->delete();
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
View
<button class="deleteRecord" data-id="{{$article->id}}"><i class="icon-bin"></i>delete</button>
AJAX
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "article/delete/"+id,
type: 'POST',
dataType: 'json',
data: {
_method: 'DELETE',
submit: true,
_token: token,
},
success: function (){
console.log("it Works");
}
});
});

route not found on ajax post

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”)

AJAX works locally; 404 on production

I have a Laravel application that works perfectly locally, but every AJAX call returns 404 when hosted. I'm unsure if this is from a sever config error, a missing php.ini setting, or something else? I've included an example of a failing call.
AJAX/JQ:
var url = "/final-review";
$("#review_note_text").change(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$('#review_note_loader').show();
var formData = {
note_text: $('#review_note_text').val(),
};
var type = "POST";
var reviewNoteUrl = url + '/review-note';
$.ajax({
type: type,
url: reviewNoteUrl,
data: formData,
dataType: 'json',
success: function (data) {
$('#failure-message-review').hide();
$('#success-message-review p').html("Saved successfully" + '×');
$('#success-message-review').show();
$('#review_note_loader').removeClass("halted-loader").hide();
},
error: function (data) {
$('#review_note_loader').addClass("halted-loader");
$('#failure-message-review p').html("Something went wrong, your record was not updated. <strong>Error Code: " + data.status + "</strong>" + '×');
$('#failure-message-review').show();
}
});
});
My Corresponding Route:
Route::post('final-review/review-note', 'FinalReviewController#update_review_note');
Controller Function
public function update_review_note(Request $request){
$validatedData = $request->validate([
'note_text' => 'nullable|string',
]);
$note = \App\ReviewNote::create([
'note_text' => $request->get('note_text'),
'author' => Auth::user()->name,
'created_at' => now()
]);
return Response::json($note);
}
SOLVED:
I had to change the "url" var in my blade template to be:
var url = "{{ url('/final-review') }}";
In my AJAX I was defining "url" as "/final-review", which led to a route of "foobar.com/final-review/params" what I really needed was "foobar.com/app-name/final-review/params".
Testing locally, I did not have "app-name" in my URL.

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.

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