Laravel with Sweet Alert redirect - php

I have made a delete modal with Sweet Alert in Laravel and it is deleting user I choose. I would however after deletion like to redirect back to users list as my destroy() method says.
<script>
$('a#delete_user').on('click', function () {
var url = $(this).attr("data-href");
swal({
title: "Delete user?",
text: "Submit to delete",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete!"
},
function () {
setTimeout(function () {
$.ajax({
type: "POST",
url: url,
data: {
_method: 'DELETE',
_token: csrf_token
},
success: function (data) {
if (data)
swal("Deleted!", "User has been deleted", "success");
else
swal("cancelled", "User has not been deleted", "error");
}
}), 2000
});
});
})
</script>
Here is the controller:
public function destroy($id)
{
User::destroy($id);
return redirect('users')->with('status', 'User Deleted!');
}
I would like to redirect to users list with message, and I have trouble doing so

In your main template file or in view file, you have to check if there is status data in session, if yes so you call sweet alert. Example code:
#if (session('status'))
<script>
$( document ).ready(
swal("{{ session('status') }}")
});
</script>
#endif

Edit js file like this:
success: function (data) {
if (data == 'success')
swal("Deleted!", "User has been deleted", "success");
window.location('Your URL');
else
swal("cancelled", "User has not been deleted", "error");
}
and the controller:
if(User::destroy($id)){
return 'success';
}else{
return 'fail';
}

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.

500 internal server error while using ajax in laravel

In my php application while using ajax , i was wanted to delete an id .it's getting csrf_token as request but not giving any response.
//JS script is here
function deleteData() {
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "{{url('deleting')}}" + "/" + id,
type: "POST",
data: {
'_method': 'DELETE',
'_token': csrf_token
},
success: function(data) {
table1.ajax.reload();
swal({
title: "Information Deleted Successfully!",
text: "You did a good job!",
icon: "success",
button: "Great !",
});
},
error: function() {
swal({
icon: 'error',
title: 'Oops...',
text: 'Something went wrong!',
timer: "3000"
});
}
})
} else {
swal("Your informatiion is safe!");
}
});
}
//laravel route is here
Route::delete('/deleting/{id}','CgpaController#delete');
//Laravel controller method is here
public function destroy($id) {
StudentInfo::destroy($id);
}
Thank you very much everyone. I found the error.I was using laravel's restful API(resource controller) where a method called destroy was doing the task . But i didn't mentioned destroy method in my route.
The route will be like this after correction.
Route::delete('/deleting/{id}','CgpaController#destroy');

Delete confirm with Sweet Alert 2 in Laravel 5.8

This is my button:
<button class="btn btn-danger" onclick="deleteConfirmation({{$wp->id}})" id="{{$wp->id}}" data-id="{{$wp->id}}"><i class="fa fa-trash"></i></button>
This is my jquery + ajax code:
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}/" + id,
data: {"_token": "{{ csrf_token() }}"},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}.then(function() {
location.reload();
});
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
This is my Laravel Controller function destroy()
public function destroy(Request $request, $id)
{
//
$delete = \App\Wypisy::where('id', $id)->delete();
return back();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Wypis został usunięty !";
} else {
$success = true;
$message = "Wypisu nie znaleziono";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
return back();
}
when I click the button, show me the confirmation window, and when I click, remove it, I will receive the message jquery.min.js: 2 POST http://localhost:8000/przedsiebiorca/wypisy/3 404 (Not Found) does not happen. As I copy the link above, the removal method works correctly in Laravel. What am I doing wrong ? Any tips?
Laravel 5.8, jquery 3.4.1
If you are passing the id with POST
Your ajax function:
// code ...
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
// code ...
Your route:
Route::post('/przedsiebiorca/wypisy/destroy', 'WypisyController#destroy');
Your Controller
public function destroy(Request $request)
{
//
$id = $request->id;
$delete = \App\Wypisy::where('id', $id)->delete();
// code ...
when i change my code for this
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
i recive in console:
jquery.min.js:2 POST http://localhost:8000/przedsiebiorca/wypisy/destroy
500 (Internal Server Error)
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # (index):395
Promise.then (async)
ue.then # sweetalert.all.js:1
deleteConfirmation # (index):390
onclick # (index):173

PHP Sweet Alert Page Redirect

I Have Used The Sweet Alert For Delete using AJAX, And I set Page redirection after Deleteing. Whenever I Click delete, It asks Confirm or not buttons,
If i click Yes-Confirm it will delete,and the Page Was Redirected. I Want
like After deleteing success message "OK Successfully Deleted" That time only page Was Refreshed,
function delete_confirm(id) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this Product Attribute!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
url: "cart-delete.php",
type: "POST",
data: {
id: id,
},
success: function(data) {
console.log(data);
swal("Done!", "It was succesfully deleted!", "success");
$('[remove_attr_' + id + ']').parents('.demo-card-wide').remove();
window.location.href = 'add-to-cart.php';
}
});
} else {
swal("Cancelled", "Your Product Attribute! is safe :)", "error");
}
});
};
Remove this line On Success
window.location.href = 'add-to-cart.php';
Write in some other action
ex. On sweet alert close action

Converting PDO to mysqli

Need help in converting PDO array execution to mysqli statements. This executes for an AJAX POST call for deleting a particular id from database with SWAL function.
<?php
require_once 'connectivity.php';
$response = array();
if ($_POST['delete']) {
$pid = intval($_POST['delete']);
$query = "DELETE FROM students WHERE id=$pid";
$stmt = mysqli_query($query,$connect);
$stmt->execute(array(':pid'=>$pid));
if ($stmt) {
$response['status'] = 'success';
$response['message'] = 'Student Deleted Successfully ...';
} else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete ...';
}
echo json_encode($response);
}
?>
This is the consecutive swal function which is to be executed once the delete button clicked.
<script>
$(document).ready(function(){
$(document).on('click', '#deleteid', function(e){
var productId = $(this).data('id');
SwalDelete(productId);
e.preventDefault();
});
});
function SwalDelete(productId){
swal({
title: 'Are you sure?',
text: "It will be deleted permanently!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'delete.php',
type: 'POST',
data: {'delete' : productId}
})
.done(function(response){
swal('Deleted!', response.message, response.status);
readDetails();
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
window.location.reload(true);
});
});
},
allowOutsideClick: false
});
}
function readDetails(){
window.location.reload(true);
}

Categories