Error 405 (method not allowed) using ajax method post laravel - ajax

There is an ajax script to remove comments under posts. When I click the delete button, I get a 405 error.
The console displays this: DELETE http://127.0.0.1:8000/id2/post/582 405 (Method Not Allowed), although the method is different url
My route Route::delete('/id{id}/post/{postId}/comment/{commentId}/delete', 'CommentController#deleteComment')->name('deleteComment');
And script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "DELETE",
data: {_token: token, id: id},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
I need that when I press delete, the record disappears, but it does not disappear. To make the entry disappear, you need to reload the page

Under the hood Laravel actually uses POST request within an _method as parameter when you perform destroy operation, so your JavaScript section should looks like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e) {
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "POST",
data: {_token: token, id: id, _method: 'DELETE'},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});

Related

Laravel/Ajax delete function not refreshing my table after success

when I add my function fetchcategory(); in my delete ajax, my table is not refreshing:
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
alert('Category Deleted!');
// location.reload();
$('#deleteCategoryModal').modal('hide');
fetchcategory();
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
});
});
for a reference, my screenshot shows the alert, showing that the delete function follows through:
another reference is that my add function here reloads the page after a new table is added:
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
another problem of mine is that I tried to add the alert and refresh function inside:
$.ajax({
type: "DELETE",
but they do not show up, so I placed them inside on(click
why is my delete ajax not refreshing my table?
UPDATE:
I am aware of location.reload(); but adding this defeats the purpose.
the data does get deleted, I have to manually refresh the whole page to see the changes though.
You can do it in ajax success. I believe fetchcategory() method is populating data to table
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// location.reload();
$('#deleteCategoryModal').modal('hide');
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function(data) {
alert('Category Deleted!');
fetchcategory();
},
error: function() {
alert('Error occured');
}
});
});
</script>

POST http://127.0.0.1:8000/unlock 405 (Method Not Allowed)

I want to pass the unlock key to route using ajax but I am not allowed to do so. The code gives me method not allowed error.
I cant see the error in my code, whether it the route error or some other error
<script>
$(document).ready(function(){
$('.result-container').hide();
$('.unlock-btn').on('click', function(){
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
});
});
</script>
So your route is a get but in ajax you are sending post request. Change it to post.
Route::post('/unlock', 'ThemeController#unlock')->name('unlock');
And also add a token in data otherwise you will get 419 error for missing CSRF.
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
"_token": "{{ csrf_token() }}",
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})

ajax is not working in laravel

$(document).ready(function () {
$('#designation').change(function () {
var opt=this.value;
// var login_url = '{{ url("ajax_crud") }}';
alert(opt);
$.ajax({
//alert(opt);
type: "post",
url:'ajax_type' ,
data: {option:opt},
success: function(data){
alert('hiii');
//$("#div_dprtmnt").html(data);
//document.getElementById("department").innerHTML=data;
}
});
});
});
this is my view page.jquery is working.but inside the ajax alert is not working.how to use $.ajax in laravel.please help me
I think this is an issue with your CSRF token. Ensure you are attaching a token on each request to protect from forgery. You can do all this like this in ajax like this:
(document).ready(function () {
$('#designation').change(function () {
var opt = this.value;
$.ajax({
_token: "{{ csrf_field() }}",
type: "post",
url: "ajax_type",
data: {
option: opt
},
success: function(data){
alert('hiii');
}
});
});
});

Laravel 5 Ajax Post route

This is my first attempt to use ajax to Post instead of Get. I get a 200 response as if it were working but the function in the controller is never being run.
I used this same concept in my ajax Get requests and they work fine but the Post is not working as expected and sortable('serialize') creates a Post variable so I need to use Post.
The alert in the success: function always runs as if it were successful but the controller function is never hit (I have it making a simple database change just to verify if it is running).
Ajax:
$(function() {
$('[id^="sortable_"]').sortable(
{
connectWith: '.sortable-line-item-list-5',
update : function (event, ui)
{
var items = $(this).sortable('serialize');
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
},
success: function()
{
alert('looks like it is working...');
},
});
}
});
$( '[id^="sortable_"]' ).disableSelection();
});
Route:
Route::post('api/sort_order_item', ['as' => 'api/sort_order_item', 'uses' =>'ApiController#SortOrderItem']);
Controller:
public function SortOrderItem()
{
$this_item = \pmms\Checklist_template_line_item::findOrFail(20);
$this_item->list_position = 1;
$this_item->save();
}
I think your problem is csrf_token,
Put this line in your blade page head section:
<meta name="csrf-token" content="{{ csrf_token() }}" />
then, update your ajax code like this :
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
success: function()
{
alert('looks like it is working...');
},
});
Let me know if it helps you

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Resources