How to delete record in laravel via ajax - php

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

Related

laravel ajax delete account and reregistering not working properly

new to laravel and Jason. i have this project at hand and i have to give the user the option to delete their account.
now i succeed in deleting the user from the database but there is another issue now.
the issue is. i register. and then i delete my account. but when i try to log in. it says the account exists. but the account no longer exists in the database. but when i tried logging in, it just logged me in and created a new id and username for the user in the database.
i tested this on multiple devices, pages, and even after days of deleting the account and they are all like that.
(it worked perfectly fine before adding the user delete option)
i thought it might be cookies but even when deleting the cookies it didn't work. someone suggested that there might be a secondary database but i didn't find anything.
(note: i noticed the update user info section and the URL is using firebase-auth. i tried searching for how to do that but i didn't find anything so i don't know how to delete the user using auth in laravel using ajax)
for testing, i removed the section of the code where it logs you out after deleting the account and in the console, i still get the user id which is weird. i have also updated the js code too.
in the console i get the:
the user's id
"response it worked"
and in the network, I'm not getting anything worth mentioning.
I'm also not getting anything in the console from logging in
edit: Thanks to Frank van Puffelen who answered i was able to solve this issue. this is how i used it in my code in case someone wanted to know
i just put this code right before the ajaxssetup function when deleting the user
const user=firebase.auth().currentUser;
user.delete().then(()=>{
console.log("account deleted succssfully");
}).catch((error) =>{
console.log(error);
});
this is what the codes look like
public\assets\js\common.js
//this is the login and register code
const firebaseConfig = {
apiKey: fireapiKey,
authDomain: authDomain,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
$("#loginWithEmail").on("submit", function (event) {
event.preventDefault();
var loginbtn45 = document.getElementById("loginWithEmailBtn");
loginbtn45.textContent = `${localLOGGINGINPLEASEWAIT}`
firebase.auth().signInWithEmailAndPassword($('#inputEmail').val(), $('#inputPassword').val()).then(function (response) {
console.log(response);
$(".loader").show();
loginbtn45.textContent = `${localLOGIN}`
if (response.user.emailVerified == true) {
$.ajax({
type: "POST",
dataType: 'json',
data: {
"_token": "{{ csrf_token() }}",
'identity': $('#inputEmail').val(),
'firstname': "D",
'email': $('#inputEmail').val(),
'lastname': null,
'login_type': "fireBaseLogin",
'device_type': 3,
'device_token': "nothing"
},
headers: {
'apikey': 123
},
url: `${baseUrl}register`,
success: function (data) {
$('.signOutModal').modal('hide');
iziToast.success({
timeout: 2000,
title: `${locallOGINsuccessfully}`,
position: "topRight"
})
localStorage.setItem('userObject', JSON.stringify(data.data));
$(".loader").hide();
},
error: function (data) {
$(".loader").hide();
console.log(data);
}
});
} else {
$(".loader").hide();
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localVerifyYourEmail}`,
position: "topRight"
});
}
})
.catch(function (error) {
console.log(error);
$(".loader").hide();
loginbtn45.textContent = `${localLOGIN}`
iziToast.error({
icon: 'fas fa-times-circle',
message: error.code,
position: "topRight"
});
})
});
//------------
$("#registerForm").on("submit", function (event) {
event.preventDefault();
var fullname = $("#fullname").val();
var email = $("#email").val();
var password = $("#password").val();
var confirmPassword = $("#confirmPassword").val();
if (password.length < 6) {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localPasswordLength}`,
position: "topRight"
});
} else {
if (password != confirmPassword) {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localPasswordNotMatch}`,
position: "topRight"
});
} else {
$(".loader").show();
$('#registerUser').text(`${localREGISTERINGPLEASEWAIT}`)
firebase.auth().createUserWithEmailAndPassword(email, password).then(function (response) {
sendingVerifyEmail();
console.log(response);
$('#registerUser').text(`${localREGISTERED}`)
$.ajax({
type: "POST",
dataType: 'json',
data: {
'identity': email,
'firstname': fullname,
'email': email,
'lastname': null,
'login_type': "firebasLogin",
'device_type': 3,
'device_token': "nothing"
},
headers: {
'apikey': 123
},
url: `${baseUrl}firebaseRegister`,
success: function (data) {
console.log(data);
$(".loader").hide();
iziToast.success({
timeout: 2000,
title: `${localRegistersuccessfully}`,
position: "topRight"
})
$('#registerForm')[0].reset();
},
error: function (data) {
$(".loader").hide();
console.log(data);
}
});
})
.catch(function (error) {
$(".loader").hide();
console.log(error);
$('#registerUser').text(`${localREGISTERED}`)
if (error.code == "auth/email-already-in-use") {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localUserAllreadyExist}`,
position: "topRight"
});
} else {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localEnterValideEmail}`,
position: "topRight"
});
}
})
function sendingVerifyEmail() {
firebase.auth().currentUser.sendEmailVerification().then(function (response) {
$('#registerUser').text(`${localREGISTERED}`)
console.log(response);
})
.catch(function (error) {
console.log(error);
$('#registerUser').text(`${localREGISTERED}`)
})
}
}
}
});
$(".delteuserbtn").on('click', function (e1){
e1.preventDefault();
$('.deltetemodal').modal('show');
$(".delteuserbtnyes").on('click', function (e2){
e2.preventDefault();
var theuser = localStorage.getItem('userObject');
if(theuser != null){
theuser = JSON.parse(theuser);
userid=theuser.id;
}
console.log(userid);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "deleteAccount/"+userid,
dataType: "JSON",
success: function (response){
console.log('response it worked');
$(".deltetemodal").modal('hide');
$(".updateProfileModal").modal('hide');
localStorage.removeItem("userObject");
$('.userName').text("")
$('.useremail').text("")
$(".usersideImage").attr('src',"")
$('.signInRemove').removeClass('d-none');
$(".userLoginDiv").css("display", "none");
iziToast.success({timeout: 2000, title: localAccDeletedSuccess,position: "topRight"})
window.location.href = `${appUrl}`;
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
$(".delteuserno").on('click', function (e){
$(".deltetemodal").modal('hide');
$(".updateProfileModal").modal('hide');
});
});
$("#updateform").on('submit',function(event) {
event.preventDefault();
$(".loader").show();
var updatedata = localStorage.getItem('userObject');
updatedata = JSON.parse(updatedata);
var formdata = new FormData($("#updateform")[0]);
formdata.append('id',updatedata.id);
console.log(formdata);
$.ajax({
url: `${baseUrl}updateProfile`,
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('apikey',apikey);
xhr.setRequestHeader('userId',updatedata.id);
},
data: formdata,
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
console.log(response)
$(".loader").hide();
iziToast.success({timeout: 2000, title: `${localUpdateSuccessfull}`,position: "topRight"})
localStorage.setItem('userObject',JSON.stringify(response.data));
$image = `${fimageUrl}${response.data.image}` ;
$(".usersideImage").attr('src',$image)
$('.userName').text(response.data.firstname)
$('.useremail').text(response.data.email)
$('.updateProfileModal').modal('hide');
},
error: function(err) { console.log(JSON.stringify(err)); }
});
});
routes/web.php
<?php
use App\Http\Controllers\ViewController;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;
Route::delete('deleteAccount/{id}' , [App\Http\Controllers\UserController::class, 'destroy']) ->name('destroy');
http/Controller/userController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class UserController extends Controller {
public function destroy($id){
/* $user = users::find($id);
$user ->delete(); */
DB::table('users')->where('id', $id)->delete();
return response()->json([
'status' =>200,
'message'=>'Account Deleted Successfully',
]);
/* $directory=storage_path('framework/views');
$files=\File::allFiles($directory);
\File::delete($files); */
}
}
As far as I can see, you do two things when you create a user:
You create the user in Firebase Authentication, by calling createUserWithEmailAndPassword .
You create a record for the user in your database.
But when you delete the user, you only delete them from the database. So that means the user can indeed still log in with Firebase Authentication, since you didn't delete it from there
To also delete the user from Firebase Authentication, call delete on their profile as shown in the documentation on deleting the current user.

DELETE not working in the Laravel Datatable

I am working with Laravel Datatable and I have stuck in one point. Below code for delete the entry in the TagManagement model. But it isn't delete the entry and worse thing is it didn't show any error. Can anybody find the error in below code?
view
$(document.body).on("click",".remove-tag", function () {
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
Controller
public function destroy($id)
{
$tagManagement = TagManagement::find($id);
$deleted = $tagManagement->delete();
if ($deleted) {
return "SUCCESS";
} else {
return "FAIL";
}
}
public function loadTags()
{
$Tags = TagManagement::all();
return DataTables::of($Tags)
->addColumn('action', function ($tag) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $tag->id . '" class="btn btn-default remove-tag remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
}
**Route**
Route::get('/delete-tag', 'AdminPanel\TagController#destroy');
Your route and controller method don't seem to correspond. First of all, it is better to use the "delete" HTTP request method for delete actions, but this is not what is causing your problem.
You defined your route as /delete-tag but in your controller you expect an $id as a parameter to your destroy method. In order for that to work you would need to have the route like this /delete-tag/{id} and construct the URL for your ajax call correspondingly on the frontend. I'm surprised you don't get the Missing argument 1 for App\Providers\RouteServiceProvider::{closure}() exception for malforming your request this way.
Laravel documentation explains very well how to define routes with parameters.
It would be helpful if you included Laravel version in your question.
Here is how it should work:
Route definition
Route::delete('/delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('delete-tag');
JS function
function deleteTag(id){
let route = '{!! route('delete-tag', ['id' => '%id%']) !!}';
$.ajax({
type: 'post',
url: route.replace('%id%', id);,
data: {_method: 'delete'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
It is not your Datatable problem, you missed some code, you did not define route & jQuery function properly, your destroy($id) function received a parameter but you do not receive any parameter in your route & you not send _token in your ajax action you need to send _token
Check My code I am edited your code.
//Change your Route
Route::get('delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('deleteTag');
//Change your function
function deleteTag(id){
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('deleteTag', '') }}/'+id,
data: {_token: '{{csrf_token()}}'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}

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

Ajax DELETE redirects even if prevented

I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.
My controller's action:
public function deletePhoto(Photo $photo)
{
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);
return response()->json(['result' => 0]);
}
return response()->json(['result' => 1]);
}
It works this way while adding photos (it adds but doesn't redirect).
Here is my ajax code:
$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.
How do I solve this problem?
Add a prevent default to your submit event. The page is redirecting because you're initiating a submit event.
e.preventDefault();
Change submit event to:
$("#form-submit-button").click(function(e){
});
try this:
$('#deleteForm').submit(function(e) {
e.preventDefault()
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
you need to add preventDefault to prevent the page from redirecting
check from console if there is errors in javascript code to work the e.preventDefault

Categories