Im trying to do a POST request with jQuery but im getting a error 405 (Method Not Allowed), Im working with Laravel 5
THis is my code:
jQuery
<script type="text/javascript">
$(document).ready(function () {
$('.delete').click(function (e){
e.preventDefault();
var row = $(this).parents('tr');
var id = row.data('id');
var form = $('#formDelete');
var url = form.attr('action').replace(':USER_ID', id);
var data = form.serialize();
$.post(url, data, function (result){
alert(result);
});
});
});
</script>
HTML
{!! Form::open(['route' => ['companiesDelete', ':USER_ID'], 'method' =>'DELETE', 'id' => 'formDelete']) !!}
{!!Form::close() !!}
Controller
public function delete($id, Request $request){
return $id;
}
The Jquery error is http://localhost/laravel5.1/public/empresas/eliminar/5 405 (Method Not Allowed).
The url value is
http://localhost/laravel5.1/public/empresas/eliminar/5
and the data value is
_method=DELETE&_token=pCETpf1jDT1rY615o62W0UK7hs3UnTNm1t0vmIRZ.
If i change to $.get
request it works fine, but i want to do a post request.
Anyone could help me?
Thanks.
EDIT!!
Route
Route::post('empresas/eliminar/{id}', ['as' => 'companiesDelete', 'uses' => 'CompaniesController@delete']);
Hello Friends 👋,
Welcome To Infinitbility! ❤️
This article will help you to solve your 405 error on your laravel project with explanation of 405 Method Not Allowed like why you are getting this error and how to solve it.
Let’s start today’s article How to solve Laravel 405 Method Not Allowed
What is 405 Method Not Allowed?
The 405 Method not allowed is an HTTP response status code that indicates that the method received in the request is known by the origin server but not supported by the target resource. There can be different causes of this error but all are related to the way we have defined routes and configured middleware in lumen. A common cause of this error is when we do not access a method in the way it is defined in routes.
why you are getting this error
405 Method Not Allowed means that the HTTP method is simply not supported. For example, a client might do a POST request on a resource where POST is not implemented or it’s meaningless.
A server generating the 405 response must also tell the client which HTTP methods it can do, using the Allow header.
405 http status code and it’s say u calling api in get but url available only in post method
Let’s understand with example
Assume you create post route in Laravel like below
use AppHttpControllersUserController;
Route::post(‘/user', [UserController::class, 'index']);
But u trying to call in get method like below
<form action="/user">
@csrf
...
</form>
But right is you have to define method in form like below
<form method="POST" action="/user">
@csrf
...
</form>
But when you using Laravel put, patch, and delete you have to define method in laravel style
<form action="/example" method="POST">
@method('PUT')
@csrf
</form>
Laravel put, patch, and delete Ajax example
$.ajax({
url: "/ajax-request",
type:"POST",
data:{
name:name,
_token: _token,
_method: "PUT",
},
success:function(response){
console.log(response);
},
});
Thanks for reading…
Доброго дня. Сразу оговорюсь — с laravel/PHP знаком давольно слабо. Возникла необходимость средствами данных технологий реализовать простое CRUD SPA.
Собственно, приложение я это реализовал, и ДО миграции на сервер оно работало (и работает) корректно.
Однако на самом сервере (ubuntu server, развернутый на azure) возникла проблема следующего характера:
При отправке ajax запроса методом POST, стабильно возвращается ошибка 405 Method Not Allowed.
Что на клиенте:
Использую AngularJS.
Сервис тестового post запроса:
postTest: function (test) { var promise = $q.resolve(false); promise = $http({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }, method: 'POST', url: '/test/', dataType: 'json' }).then(function successCallback(responce) { return responce; }, function errorCallback(response) { return { error: response }; }); return promise; },
Что на сервере:
PHP
//route/web
Route::get('/test/', 'Test@get_test');
Стоит также отметить, что запросы GET/PUT/DELETE типов отрабатывают совершенно правильно (проверял, в частности на приведенном выше тестовом сервисе).
Еще одна странность состоит в том, что для добавления элемента мной тоже используется POST, но почему-то в этом случае ошибки не происходит.
Надеюсь, более компетентные, нежели я, коллеги смогут подсказать, что можно в данном случае сделать/куда копать.
I know there are several posts about 405 Errors from using AJAX delete. However, none of the solutions from the posts I found worked for me.
I have a view with a table displaying all the products from my database table. On each row there is a delete button to delete the product like so:
{!! Form::open(['method' => 'DELETE', 'route' => ['slider.destroy', $slide->id]]) !!}
<button type="button" class="deleteproductModal btn btn-xs btn-default btn-flat"
data-toggle="modal"
data-product_token="{{ csrf_token() }}"
data-product_name="{{ $slide->title_slider }}"
data-product_destroy_route="{{ route('slider.destroy', $slide->id) }}">
<i class="fa fa-trash"></i>
</button>
{!! Form::close() !!}
On button click, the following javascript executes which calls the destroy method in the controller to delete the product from the database:
$('button.deleteproductModal').click(function()
{
var productRoute = $(this).attr("data-product_destroy_route");
var productName = $(this).attr("data-product_name");
var productToken = $(this).attr("data-product_token");
deleteproduct(productRoute, productToken, productName);
});
function deleteproduct(productRoute, productToken, productName)
{
swal({
title: "Window product Deletion",
text: "Are you absolutely sure you want to delete " + productName + "? This action cannot be undone." +
"This will permanently delete " + productName + ", and remove all collections and materials associations.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Delete " + productName,
confirmButtonColor: "#ec6c62"
}, function()
{
$.ajax({
type: "DELETE",
url: productRoute,
headers: { 'X-CSRF-TOKEN' : productToken }
})
.done(function(data)
{
swal("Window Product Deleted!", productName + " Window Product was successfully delete.", "success");
})
.error(function(data)
{
swal("Oops", "We couldn't connect to the server!", "error");
});
});
}
My controller is a resource controller. Here is the route:
Route::resource('slider','BackendSliderController');
Here is the destroy method from the controller being called.
public function destroy($id)
{
$home= Slider::find($id);
unlink($home->featured_image);
$home->delete();
notify()->flash('<h3>Deleted successfully</h3>', 'success', ['timer'=>2000]);
return redirect('slider');
}
when i delete the product i get oops we couldnt connect to the server sweet alert error but when i fresh the page the data is deleted….any help?
Having the same issue here.
I guess you and I are trying to send a post request to an unlocalized URL and hopping for the proper redirection. Well, it took me an hour to remember that we can’t «just redirect» post requests. Especially not with a HTTP 301/302. So the client ignores the redirect an Laravel throws a MethodNotAllowedHttpException.
Redirecting a POST request requires a HTTP 307 (which isn’t technically a «follow the rabbit» redirect. It tells the client to resend his request to different URI).
By glancing over the source code and the issues, this package had support for 307 HTTP responses at some point as mentioned in the Changelog v0.12.0, #62, #63 and #215, but now it’s missing for some reason.
@mcamara may you bring back HTTP 307 response support. Why has it been removed?