I am developing an ASP MVC 5 web application using SQL Server. I am trying to delete a profile (client in database) via a button with javascript function.
Clicking on the button, the profile is deleted but the validation dialog doesn't appear. I don't know what the reason is but I doubt that there is an issue with the javascript code.
I tried also to create another button without submit, in order to verify the sweetAlert process. And it worked well.
This is my View :
#using (Html.BeginForm("Delete", "Client", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<input type="submit" value="Delete" class="btn btn-default" onclick="remove()">
}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">function remove() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover your profile!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your profile has been deleted!", {
icon: "success",
});
} else {
swal("Your profil is safe!");
}
});
}
</script>
My Controller :
[HttpPost]
public ActionResult Delete(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.DeleteClient(id))
{
TempData["Message"]= "Client Deleted Successfully";
}
Session.Abandon();
return RedirectToAction("Index", "Home");
}
catch
{
return View();
}
}
UPDATE :
View :
<input type="button" value="Delete" class="btn btn-default" onclick="remove()">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
function remove() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover your profile!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
type: "POST",
url: "/Client/Delete",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Poof! Your profile has been deleted!", {
icon: "success",
}).then(function () {
window.location.href = "/Home/Index"
});
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
else {
swal("Your profil is safe!");
}
});
}
</script>
You are trying to update onclick default behavior but you're not using preventDefault in your javascript code.
event.preventDefault()
Related
Hello guys I'M having an issue with my sweetalert delete confirmation. When I click on "Yes Delete it!" nothing happens and there are no errors showing in my console please guys I seriously need help this has kept me on deck for a long time now. I really be grateful if I get quick responses.
This is my blade.php
<button onclick="deleteConfirmation({{$poster->id}})" type="button" class="btn btn-danger delete-confirm offset-md-2">Delete</button>
<script type="text/javascript">
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Are you sure you want to delete this?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: true
}).then(function (e) {
if (e.value) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'DELETE',
url: "{{ url('delete-post') }}" + '/' + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
And here is my controller
public function deletepost($id)
{
dd($id);
DB::table('posters')->where('id', $id)->delete();
return back()-> with('post_add', 'Post deleted Successfully');
}
And my route
Route::delete ("/delete-post/{id}", [PosterController::class, "deletepost"])->name("poster.delete");
when i click the button confirm on swal nothing happens, i dont khow if the problem is the ajax code
or somthing else
but when i delete the ajax code from the swal code it works fine and shows the sweetalert so i think the probleme comes from ajax
<script>
function deleteData(id) {
swal({
title: "Suppression",
text: "Veuillez confirmer la suppression",
type: "warning",
showCancelButton: true,
confirmButtonText: "Confirmer",
cancelButtonText: "Annuler",
reverseButtons: true
}.then(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "DELETE",
url: "{{url('eventment/type')}}/" + id,
data: {
_token: CSRF_TOKEN
},
dataType: "JSON",
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
} //success
});
})
) //swal
} //deleteData
</script>
Delete button
<button class="btn btn-danger" onclick="deleteData({{$type->id}})" >Supprimer</button>
route file
Route::delete('eventment/type/{id}','TypeController#destroy')->name('type.destroy');
controller
public function destroy($id)
{
$type = EventType::where('id', $id)->delete();
return redirect()->to(route('admin.type.index'))->withFlashSucces('Le Type A Bien Etait Supprimé');
}
You can do it without ajax.first your button make it as a form
<form id="del_event" action="{{ route('type.destroy',$type->id) }}" method="post"style="display: inline;">
{!! method_field('delete') !!}
{{ csrf_field() }}
<button class="btn btn-danger" type="submit" id="del_id">Supprimer</button>
</form
Button has a id "del_id" when it click call a function below there
<script>
$("#del_id").on('click', function (e) {
e.preventDefault();
swal({
title: "Suppression",
text: "Veuillez confirmer la suppression",
type: "warning",
showCancelButton: true,
confirmButtonText: "Confirmer",
cancelButtonText: "Annuler",
}).then((result) => {
if(result) {
$("#del_event").submit();
}
}
)
;
});
</script>
Your destroy function
$type=EventType::find($id);
$type->delete();``
I have a delete button when user click it I want a sweet alert which asks for confirmation and once the user click yes and confirm then I want to disappear current confirmation alert and show another alert which tells user deleted and then after 2 seconds page reloads.
i have done it but my issue is when user click on confirmation alert he get the another alert but with some trails of previous alert. (this is the snip showing trails in red boxe) (I did not uploaded them here because I can not due to reputation).
my js is
function deleteUser(userRow) {
var objUserRow = jQuery.parseJSON(unescape(userRow));
swal({
title: "Are you sure?",
text: "You will not be able to recover this user again",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
closeOnClickOutside: false,
}, function (isConfirm) {
if (isConfirm) {
$.ajax({
url: '../users/deleteUser',
type: 'POST',
data: objUserRow,
success: function (data) {
if (data == "success") {
//swal("User Deleted!");
swal({
title: "Deleted!",
text: "User has been deleted successfully!",
type: "success",
showConfirmButton: false,
closeOnClickOutside: false
});
setTimeout(function () { location.reload(); }, 2000);
} else if (data == "error") {
//this could be due to server side validation or server side error
swal("Error!", "An error has occured at server side", "error");
}
},
error: function () {
swal("Error!", "An error has occured at server side", "error");
}
});
}
});
}
I can not get what I am doing wrong. Please help
Try to use promises
https://sweetalert.js.org/guides/?_sm_au_=i0HmMJQJFSN6506q#using-promises
swal({
title: "Are you sure?",
text: "You will not be able to recover this user again",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
closeOnClickOutside: false,
}).then((isConfirm) => {
if (isConfirm) {
$.ajax({
url: '../users/deleteUser',
type: 'POST',
data: {},
success: function (data) {
if (data == "success") {
//swal("User Deleted!");
swal({
title: "Deleted!",
text: "User has been deleted successfully!",
type: "success",
showConfirmButton: false,
closeOnClickOutside: false
});
setTimeout(function () { location.reload(); }, 2000);
} else if (data == "error") {
//this could be due to server side validation or server side error
swal("Error!", "An error has occured at server side", "error");
}
},
error: function () {
swal("Error!", "An error has occured at server side", "error");
}
});
}
});
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
When I use Ajax sweet Alert doesn't show image. I'm working with laravel.
This is my code, if I delete the ajax function or I use a image from another website it works.
I really have no clue, I think laravel need some kind of authetication from a Ajax request. Please help me out!
$(document).ready(function() {
$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this team!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal({
title: "Checking...",
text: "Please wait",
icon: icons,
button: false,
allowOutsideClick: false
});
$.ajax({
url: linkURL,
type: 'GET',
success: function(result){
swal("The team was deleted!");
}
});
} else {
swal("The team was NOT deleted!");
}
});
}
});
I make my EDIT view a dialog box and i need to pass AntiForgeryToken with it. But I've tried several times and still I can't pass it.
$("#EditSave").click(function(e) {
e.preventDefault();
$.ajax({
url: 'PIS/Edit',
type: "POST",
dataType: 'json',
data: $('form').serialize(),
success: function (data) {
if (data.Save) {
dialog.dialog('close');
var notification = {
type: "success",
title: "Successfully",
message: "save ",
icon: 'glyphicon glyphicon-ok-sign'
};
showNotification(notification);
updatePartial();
}
if (data.AlreadyExist) {
var notification = {
type: "danger",
title: "Warning!",
message: "Already Exist",
icon: 'glyphicon glyphicon-exclamation-sign'
};
showNotification(notification);
}
if (data.Back) {
var notification = {
type: "danger",
title: "Warning!",
message: "Information was not successfully saved. Please check required fields.",
icon: 'glyphicon glyphicon-exclamation-sign'
};
showNotification(notification);
}
else {
debugger
dialog.dialog('close');
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
})
return false;
})
This is my controller action and I need to pass the token on my view so that cross-side scripting can be prevented because this is an Edit view in a form of a dialog box.
public async Task<PartialViewResult> Edit(string id)
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult>Edit(PISEditViewModel viewModel)
{
return Json(new {Back = true });
}
This is the error message i got when passing $('form').serialize()
The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.