Cancel button not working in sweetalert - javascript

when i am clicking on cancel button in sweetalert.js it still running the AJAX call i want to terminate the process on cancel button.
swal({
title: " Asking price for "+askData[0]+"?",
text: "If you are sure press OK or edit this text",
type: "input",
inputType: "text",
inputValue: "Hello "+askData[1]+", I am interested in buying your "+askData[0]+" of Variety :"+askData[3]+". Please update the Price!",
showCancelButton: true,
closeOnCancelButton:true,
closeOnConfirm: false,
showLoaderOnConfirm: true
}, function(inputValue) {
if (inputValue === "") {
swal.showInputError("Please write something !");
return false;
}
$.ajax({
url: urlEnq,
type: "GET"
});
$.ajax({
url: 'saveUserMessage',
type: "POST",
data: {fieldUserId:fieldUserId,filedUserCompanyId:filedUserCompanyId,message:inputValue},
success: function(data)
{
swal("Done!", "Your message has been successfully sent.", "success");
}
})
.error(function(data) {
swal.showInputError("Please write something !");
});
});
});
});

Related

Laravel Hiding Validation Errors Message with Ajax when is true

i have implement the validation errors message with ajax successfully, but when the previous input form is true, the previous error in that input form is not hiding. Anyone can help me to hide the previous error if input form is true?
This is my javascript code :
$.ajax({
url: `${window.url}/income`,
type: "POST",
data: {
_token: CSRF_TOKEN,
detail: arrValues,
data_contact_id,
total,
description,
invoice,
transaction_date,
to_account_id,
},
dataType: "JSON",
success: function (response) {
console.log(response);
if (response.status) {
Swal.fire({
icon: "success",
type: "success",
title: response.message,
showConfirmButton: true,
}).then((result) => {
window.location.href = `${window.url}/income`;
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
let fields = [
"data_contact_id",
"invoice",
"transaction_date",
"to_account_id",
"description",
];
fields.map((field) => {
$(`#${field}`).removeClass("is-invalid");
$(`.${field}-error`).html(``);
});
let errors = jqXHR.responseJSON.errors;
$.each(errors, function (key, value) {
$(`#${key}`).addClass("is-invalid");
$(`.${key}-error`).append(`
<span class="text-danger" style="font-size: 0.8rem">
${value.map((v) => "<strong>" + v + "</strong><br>")}
</span>
`);
console.log("Field : ", key);
});
Swal.fire({
icon: "error",
type: "error",
title: "Error!",
showConfirmButton: true,
});
},
});
In my controller i have return validation error json from Validator::make()
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()]);
}
$.ajax({
beforeSend: function(){
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();
},
complete: function(){
// Handle the complete event
}
error : function(){
// Handle the error event
}
// ......
});
$(`#${key}`) add class key_of_form
$(`.${key}-error`) add class error_of_key
before submit of form or beforeSend of ajax you need reset error messages same as :
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();

Receiving 66:285 Uncaught TypeError: Cannot read property 'then' of undefined

I have designed a simple ajax request for deleting a file from database in mvc. for that i am using javascritp ajax with swal prompt for delete. But it is not working. I am getting .then undefined error.
Here is the code--
$(".btnDel").click(function () {
var NewFileName = $(this).val();
var id =#Model.Pd.Id;
console.log(id);
console.log(NewFileName);
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "#Url.Content("~/ManageProducts/DeleteExistingFile")/",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
Thanks for the edit. The snippet below defines id and NewFileName for testing and uses example.com for the POST - if you try to delete the file you get the "oops" message. In other respects it should be the same as the code in the post.
const id = "example_id";
const NewFileName = "example.pdf";
//**********************************
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "https:www.example.com/delete",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
I am at a loss to explain why the snippet works but running it in VS says swal returns undefined. I would test the code in a browser first to see if it still errors.
Disclaimer: this is not the answer. . . yet. I am happy to delete it if anyone solves the mystery.

How to ask for confirmation in toastr before deletion

I'm working in PHP LARAVEL , what i want is a toastr to delete an item from database.
So when the button is clicked to delete, the toastr should ask "Are you sure to delete?" in ajax.
If selected "OK" the data should be deleted, if selected "Cancel" the data should not be deleted.
How to accomplish this?
Below is my ajax code:
//to unfollow feed
$('#following').click(function (e) {
e.preventDefault();
var formData = $("#unfollowFeed").serialize();
$('.error-msg').html('');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'unfollow',
type: 'POST',
data: formData,
success: function (data) {
var id=$('#feed_id').val();
$("#feedId li[feed-id=" + id + "]").remove(); //to remove <li> of removed feed from sidebar.
toastr.error('The feed was removed.');
$('#follow').show();
$('#following').hide();
}
});
});
This is my view part:
<a href style="{{ $status == 0 ? 'display:none;' : '' }}" class=" btn btn-sm btn-primary following" id="following" >{{ __('Following') }}</a>
Can anyone help me with this?
You can use Sweetalert of bootstrap
$('#following').click(function (e) {
e.preventDefault();
var formData = $("#unfollowFeed").serialize();
$('.error-msg').html('');
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function() {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'unfollow',
type: 'POST',
data: formData,
success: function (data) {
var id=$('#feed_id').val();
$("#feedId li[feed-id=" + id + "]").remove(); //to remove <li> of removed feed from sidebar.
toastr.error('The feed was removed.');
$('#follow').show();
$('#following').hide();
}
});
});
});
<!DOCTYPE html>
<html>
<body>
<p>Example: Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
You can use the inbuilt confirm box:
$('#following').click(function (e) {
var response = confirm("Are you sure to delete?");
if (response == true) {
e.preventDefault();
var formData = $("#unfollowFeed").serialize();
$('.error-msg').html('');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'unfollow',
type: 'POST',
data: formData,
success: function (data) {
var id=$('#feed_id').val();
$("#feedId li[feed-id=" + id + "]").remove(); //to remove <li> of removed feed from sidebar.
toastr.error('The feed was removed.');
$('#follow').show();
$('#following').hide();
}
});
} else {
/* do anything on Pressed cancel*/
}
});
You can use sweetalert for this purpose.
Sweet alert docs
Add this cdn <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
then
<script>
$('#following').click(function (e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary
file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
ajaxcall(); //calling ajax function
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
});
function ajaxcall()
{
$('.error-msg').html('');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'unfollow',
type: 'POST',
data: formData,
success: function (data) {
var id=$('#feed_id').val();
$("#feedId li[feed-id=" + id + "]").remove(); //to remove <li> of removed feed from sidebar.
toastr.error('The feed was removed.');
$('#follow').show();
$('#following').hide();
}
});
}
</script>

Sweet alert not triggering my php file

I am using sweet alerts 2 for my webpage and i am trying to trigger my php file when the user presses delete on the sweet alert, if they do not do nothing. For some odd reason it is not triggering the php file, the pop does not come up either, i ran a simple sweet alert in the console just to see if i have the correct scripts in and it works fine.
I have this code so far :
<form method="post" id="deleteF" name="delete">
<button type="submit" name="delete" class="btn btn-xl btn-mrg" id="delete" >Delete</button>
</form>
$(document).on('submit', 'deleteF', function (e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "You can not recover your account if you delete!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.ajax({
type: 'POST',
url: 'lib/delete.php',
success: function (data) {
},
error: function (data) {
swal("NOT Deleted!", "Something happened!", "error");
}
});
} else {
swal("Cancelled", "Your account was not deleted", "error");
}
});
return false;
});
My php file only has a simple echo in it just to for testing, any help would be greatly appreciated, Note i only included the relevant parts, the sweet alert section is enclosed in script tags
<a data-id='" . $rows['id'] . "' id='delete_id' class='btn btn-danger btn-sm'<span class='glyphicon glyphicon-trash' href='javascript:void(0)'></span>delete</a>
<script>
$(document).ready(function() {
$(document).on('click', '#delete_id', function(e) {
var id = $(this).data('id');
SwalDelete(id);
e.preventDefault();
});
});
function SwalDelete(id) {
Swal.fire({
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: 'office_info_delete.php',
type: 'POST',
data: 'id=' + id,
dataType: 'json'
})
.done(function(response) {
Swal.fire('Deleted!', 'Your file has been deleted.', 'success')
})
.fail(function() {
Swal.fire('Oops...', 'Something went wrong with ajax !', 'error')
});
});
},
});
}
</script>

How can i put ajax in confirm button?

Hi friends i am trying to put ajax url in confirm button to update something in Database.
So i do this in JavaScript Section
function freeze_account() {
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}
and this is code for update
$manager_id = $_POST['manager_id'];
$state = '0';
$update=runQuery("UPDATE `users` SET `userStatus` =:userS WHERE `userID`=:user_id");
$update->bindparam(":userS",$state);
$update->bindparam(":user_id",$manager_id);
$update->execute();
My problem is when i press confirm button ajax works and go to another page but nothing happen in database.
What is wrong in my code Or Maybe I miss something?
any help any idea i will be grateful
Best Regards
look how i solved my problem
Maybe one benefit of my code
Thanks for every one suggestions or helping me
function freeze_account() {
var pid = $('#manager_id').val();
bootbox.dialog({
message: "Are you sure you want to Freeze this account ?",
title: "<i class='glyphicon glyphicon-trash'></i> Freeze !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Freeze!",
className: "btn-danger",
callback: function() {
$.post('update_freeze.php', { 'pid':pid })
.done(function(response){
bootbox.alert(response);
location.reload();
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
}
You need to set up an event listener on your button. Firstly, ensure you have an ID on your button so we can grab it.
Now, we create the event listener:
$("#button").on("click", freeze_account());
And, now when you click the button the ajax call should go through successfully.
However, it will still redirect yo due to its default behaviour.
To override this, simply prevent the default event:
function freeze_account(event) {
event.preventDefault(); // stops the button redirecting
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}

Categories

Resources