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");
}
});
});
Related
I've set up two buttons which when clicked are just sending their values to my controller, then I am trying to send back AJAX HTML to show the users profile on the main page. I can't get the input id to make it to the controller no matter what I try.
Here's the HTML:
<ul class="signup-li">
#foreach($participants as $participant)
<button type="submit" name="id" value="{{$participant->id}}">
{{$participant->phone}}
</button>
#endforeach
</ul>
Here is my JS:
$(document).ready(function(){
$("button").click(function() {
var id = $(this).val();
console.log(id);
$.ajax({
type:'POST',
url:'/get-profile/',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "id" : id },
success: function(data){
console.log('hi');
},
error: function(xhr,textStatus,thrownError) {
alert(xhr + "\n" + textStatus + "\n" + thrownError);
}
});
});
});
Here is my controller function:
public function getProfile(Request $request)
{
$id = $request->input('id');
Log::info($id);
$participant = Participant::where('id','=',$id)->first();
$returnHTML = view('ajax.user-profile')->with('participant', $participant)->renderSections()['content'];
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
What am I doing wrong? I try to log the request and nothing comes through. I have CSRF disabled for this route. The issue is that the participant is not found because the ID is not getting to the controller. Why isnt it making it?
You may add dataType: 'json', to your $.ajax({...}) call
I know there are similar questions relating to this issue, but I have tried my copy after those with the right answer, yet still to no avail.
I keep getting this error:
BadMethodCallException Method delete does not exist. in Macroable.php (line 74)
To be quick, here is my controller:
public function destroy(Subject $subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
Here is my route:
Route::delete('/subjects/delete/{subject}', 'SubjectsController#destroy');
Here is my view:
<td>
<a data-token="{{ csrf_token() }}" id="delete" data-id="{{$subject->id}}" data-toggle="tooltip" title="Edit" href="/subjects/{{$subject->id}}" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>
</td>
and last my scripts:
$(document).on('click', '#delete', function(event) {
event.preventDefault();
/* Act on the event */
// id of the row to be deleted
var id = $(this).attr('data-id');
var token = $(this).data("token");
console.log(id);
// row to be deleted
var row = $(this).parent("td").parent("tr");
var message = "subject";
bootbox.dialog({
message: "Are you sure you want to Delete this "+message+"?",
title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data: {
"id": id,
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
}
}
});
});
Here is what I get when I don php artisan route:list
I don't know the technical details of why it is working this way but it seems the the problem was coming from my controller destroy method. So, this was all I had to do:
controller code:
public function destroy($subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
script:
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data:{"id": id, "_method": 'DELETE'}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
route:
Route::delete('/subjects/delete/{subject}','SubjectsController#destroy');
The main thing for me was to remove the Subject from the destroy() parameter and it work.
If any of you know why it's working that please provide and explanation so that I can understand it too. Thanks!!
Change the type in your ajax call to POST, the _method field in the data object is all that is needed. This is how your ajax call should look. Laravel "fakes" the DELETE method by using the _method field to determine the http verb.
$.ajax({
type: 'POST',
url: '/subjects/delete/'+id,
data: {
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
SOLUTION IN LAST COMMENT OF ANSWER
I have this function here
function delTag(e, name){
var tag_id = $(e).attr('rel');
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}
I call it like this:
#foreach($tags as $tag)
<button onclick='delTag(this, "{{$tag->name}}")' rel={{$tag->id}} type="button" data-dismiss="modal" class="btn btn-danger">Yes</button>
#endforeach
And i get this:
My record is deleted from the database correctly, but, ajax throws error. Why is this happaneing?
Here is my whole route if it helps...
Route::get('admin/', 'AdminController#getAdminIndex')->name('admin.index');
Route::delete('admin/users/{id}', 'Auth\\RegisterController#destroy')->name('admin.users.destroy');
Route::put('admin/users/{id}', 'Auth\\RegisterController#update')->name('admin.users.update');
Route::resource('/admin/posts', 'PostController');
Route::resource('/admin/roles', 'RoleController');
Route::delete('/admin/comments/{id}/{user_id}', 'CommentsController#destroy')->name('comments.destroy');
Route::resource('/admin/comments', 'CommentsController', [
'except' => ['store', 'destroy']
]);
Route::get('/administrator', 'AdminController#getAdmin')->name('admin');
Route::put('/admin/comments/approve/{id}', 'CommentsController#updateApprove')->name('admin.comments.approve');
Route::put('/admin/tags/associate/{tagName}', 'TagController#updateAssociation')->name('admin.tags.associate');
Route::put('/admin/categories/associate/{categoryName}', 'CategoryController#updateAssociation')->name('admin.categories.associate');
Route::resource('/admin/categories', 'CategoryController');
Route::resource('/admin/tags', 'TagController');
Route::get('/admin/pages/tables/{user_id}', 'AdminController#getTables')->name('admin.pages.tables');
Route::get('/admin/pages', 'AdminController#getIndex')->name('admin.pages.index');
With the ajax call you need also to provide csrf_token.
You can keep it on the page in the hidden input field, like this for example:
<input id="csrf" type="hidden" name="_token" value="{{ csrf_token() }}">
And then add it to your ajax call with key "_token". So your delTag function will become something like this:
function delTag(e, name){
var tag_id = $(e).attr('rel');
var csrfToken = $("#csrf").val(); // here you're obtaining token from the page
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
data: {
"_token": csrfToken //Here you're passing the token
},
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}
I'm getting the next error:
jquery-2.2.4.min.js:4 DELETE http://company.dev/admin/portfolio/settings/category/delete/7 500 (Internal Server Error)
I'm not sure what it is because I think I have the right route and also giving the csrf token (still fairly new to laravel)
Route:
Route::delete('/admin/portfolio/settings/category/delete/{id}', [
'as' => 'categoryDelete',
'uses' => 'PortfolioController#destroy'
]);`enter code here`
Ajax:
$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "/admin/portfolio/settings/category/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
Delete button:
<button class="deleteProduct" data-id="{{ $category->category_id }}" data-token="{{ csrf_token() }}" >Delete Category</button>
Delete function:
public function destroy(Request $request, $id)
{
Category::find($id)->delete();
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}
Either your Controller or Model has some error. May be syntax error. Try checking Console > Network > XHR. The error ajax request will be in red color if you are using Google Chrome.
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