I am getting a 405 (Method Not Allowed) in Laravel while trying to delete an item using ajax. Someone please help.
Here is my route
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/destroy', 'PagesController#destroy');
Auth::routes();
Here is my ajax code
function confirmDelete(id){
//alert('Delete post id-'+id);
$.ajax({
type: 'post',
url: 'blogs/destroy',
data: {'id' : id},
dataType: 'json',
cache: false,
success: function(res){
console.log("worked");
alert(res);
}
})
}
Here is my controller
public function destroy (Request $request){
$id = $request->id;
echo json_encode ($id);
// $blog = Blog::findorFail ( $id );
// $blog->delete ();
// return response(['msg'=>'Post deleted',
'status'=>'success']);
// return redirect::to ( '/blogs' )->with ( 'success', 'Post
successfully deleted!' );
}
The reason you're getting this error is because your request URI /blog/destroy doesn't match the route definition /destroy.
Therefore either change the route to
Route::post('/blog/destroy', 'PagesController#destroy');
or change your request
$.ajax({
type: 'post',
url: '/destroy',
// ...
})
Try this for routes->
Route::post('/blog/destroy', 'PagesController#destroy')->(destroyPage);
Try this inside ajax:
$.ajax({
type: 'post',
url:'{{ route('destroyPage') }}',
// ...
})
Got the answer just login to my server and disable the ModSecurity and its works, so, later on, I configure the ModSecurity to not get the 405 methods not allowed error on live server.
Related
I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];
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.
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'))
});
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
I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');