Deleting a record in Laravel 5.3 using AJAX - php

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.

Related

AJAX data is not submitting to Laravel controller - Laravel 6

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

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");
}
});
});

Laravel Update Database with ajax

Hey guys I'm using laravel 5.7 and I'm attempting to make a ajax post request to update my database. The ajax would post based on a checkbox on change function. Example if i toggle off the checkbox it would send a request and update my status to Inactive in my User table. After attempting it, i had an error of 405 (Method Not Allowed). Anyone able to note what am i doing wrong? Sorry if there are some wrong codes or syntax in my codes as I'm very new to Ajax. Any help would be appreciated.
Ajax
$(document).ready(function(){
$.ajax({
type:'get',
url:'{!!URL::to('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
console.log(checkBox);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(){
$.ajax({
type: "POST",
url : '{!!URL::to('admin/{admin}')!!}',
success:function(data){
console.log(data);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
});
Route
Route::resource('admin','AdminController'); << I'm using the update method from the resource controller
Controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
Form
{!!Form::open(array('action'=>['AdminController#update',$item->u_id],'method'=>'POST','id'=>'update'))!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="u_id" id="u_id" value="{{$item->u_id}}">
<label class="custom-control custom-checkbox">
<input type="checkbox" id="switch-{{$item->u_id}}" class="custom-control-input">
<span class="custom-control-indicator"></span>
</label>
{{-- <button class="btn btn-primary">Update</button> --}}
{{Form::hidden('_method','PUT')}}
{!!Form::close()!!}
UPDATE
I have managed to "pass" the u_id to my post request by getting the id through target.id and splitting it with -. It is not the most elegant way but it works. But now im getting an error
POST http://manageme.test/admin/%7B2%7D 500 (Internal Server Error)
Here is what i have updated in my codes.
$('#switch-'+data[i].u_id).change(function(e){
console.log(e.target.id);
var s = e.target.id;
var split = s.split('-')[1];
$.ajax({
type: "POST",
url: `{!!url('admin/')!!}/{${split}}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success:function(data){
console.log(data);
}
});
});
these are inside my update controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
I have also looked at the error inside the network tab of the dev tools the error message from laravel is message: "Trying to get property 'status' of non-object". I think it cant find any $user inside the update method
Instead of:
"{!!URL::to('admin/{admin}')!!}"
write :
`{!!url('admin/')!!}/${data[i].u_id}`
and add _token and _method params to your ajax data
and write like this:
$(document).ready(function () {
$.ajax({
type: 'get',
url: '{!!url('findStatus')!!}',
success: function (data) {
data.forEach(d => {
console.log(d);
if (d.status == "Active") {
$(`#switch-${d.u_id}`).prop('checked', true);
}
else if (d.status == "Inactive") {
$(`#switch-${d.u_id}`).prop('checked', false);
}
$(`#switch-${d.u_id}`).change(function () {
console.log(d);
//changed###########
$.ajax({
type: 'POST',
url: `{!!url('admin/')!!}/${d.u_id}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success: function (data) {
console.log(data);
}
});
//###################
});
});
},
error: function (data) {
console.log('ERROR');
}
});
});
Solution
I managed to fix it the problem was coming from the route trying to pass the u_id of the user and finding the user's data. So instead of typing the url inside, i made a variable to pass the route and u_id together. Here are the codes
Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'get',
url:'{!!url('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(e){
var s = e.target.id;
var split = s.split('-')[1];
var url = '{{route('admin.update','split')}}';
$.ajax({
type: 'POST',
url: url,
data: { _token: "{{ csrf_token() }}", _method: "PUT" ,u_id: split},
success: function(data) {
console.log(data['message']);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
Update method
public function update(Request $request, $id)
{
$user = User::find($request['u_id']);
if($user->status == "Active")
{
$user->status = "Inactive";
$user->save();
return response()->json(['message' => 'Update to Inactive']);
}else{
$user->status = "Active";
$user->save();
return response()->json(['message' => 'Update to Active']);
}
}
DONT forget to add the meta tag onto the document header for csrf token
<meta name="csrf-token" content="{{ csrf_token() }}">

MethodNotAllowed on deleting an item with AJAX and Laravel

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:');
}
});
}

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