Set isConfirmed to true after timer runs out on SweetAlert2 - javascript

I am using sweetalert2 when confirming an input from user. I am using a dialog with two buttons , confirm button and cancel button, also I added a timer. When submit button is clicked everything works fine ( ajax is called ) but when timer runs out I want the same result as confirm button. I have tried adding Swal.isConfirmed = true, result=true but didn't get desired one.
Swal.fire({
title: 'Дали сакате да ги зачувате промените?',
showDenyButton: true,
confirmButtonText: 'Зачувај',
confirmButtonColor: '#00CA4E',
denyButtonText: `Откажи`,
denyButtonColor: '#FF605C',
html: '<strong></strong> секунди.<br/>',
timer: 3000,
didOpen: () => {
timerInterval = setInterval(() => {
Swal.getHtmlContainer().querySelector('strong')
.textContent = (Swal.getTimerLeft() / 1000)
.toFixed(0)
}, 100)
},
willClose: () => {
clearInterval(timerInterval);
Swal.isConfirmed = true;
}
}).then((result) => {
/* Read more about isConfirmed, isDenied below */
if (result.isConfirmed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("SubstitutionAddPlayers","Scoreboard")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
} else if (result.isDenied) {
//Swal.fire('Changes are not saved', '', 'info')
}
})
I want when timer runs out, result in then to be true and ajax call to be executed.

If a SWAL2 is dismissed from a timer, you can use result.isDismissed the same way as result.isConfirmed in any conditional statement.
if (result.isDismissed) {
// .. code if timer is dismissed
}
if (result.isConfirmed) {
// .. code if timer is confirmed
}
This is the result response if you remove all buttons and let it be:
{isConfirmed: false, isDenied: false, isDismissed: true, dismiss: 'timer'}
So try adding
if (result.isDismissed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("
SubstitutionAddPlayers ","
Scoreboard ")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
}
Note: Consider disabling outside click on that specific one maybe.

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();

Function returning true despite promise evaluating to false

I'm having a real hard time figuring out the behaviour of Promises. I'm using Vue and the vee-validate library, which allows for manual validation of a form via:
this.$validator.validate()
However, when I try to use it I get weird behaviour:
async isFormValid() {
return await this.$validator.validate();
},
Whenever I submit a form with errors, the form sends the AJAX request:
onApprove() {
if (!that.isFormValid) {
return false;
}
$.ajax({
...
});
return false; // Modal never closes unless AJAX is successful.
},
Additionally, I've tried the following construct:
onApprove() {
this.$validator.validate().then(result => {
if(result) {
$.ajax({
...
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
But this doesn't work either. I've found a work-around by doing this:
isFormValid() {
this.$validator.validate();
return Object.keys(this.fields).every(key => this.fields[key].valid);
},
But if someone could explain what I'm misunderstanding about the `Promise, that would be great.
Edit
Full onApprove example (always returns true regardless of validation:
onApprove() {
that.$validator.validate().then(result => {
if (result) {
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
This method also doesn't work (return false first):
onApprove() {
that.$validator.validate().then(result => {
if (!result) {
return false
}
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
return false; // Modal never closes unless AJAX is successful.
});
},
So #Axnyff found this semantic-ui beug report, which led me to the solution:
onApprove() {
that.$validator.validate().then((result) => {
if (result) {
$.ajax({
...
},
complete() {
$('#modify_user_modal').modal('hide'); // Manually hide.
},
});
}
});
return false; // Modal never closes.
},

jQuery PHP Ajax Check User Logged in show modal

I have jQuery PHP Ajax to check user logged in or not.
JS
jQuery(document).ready(function()
{
setInterval(function()
{
jQuery.ajax({
url: 'chkLoggedin.php',
type: 'POST',
success:function(response)
{
if(response == "sessionExpired")
{
bootbox.dialog(
{
message: "Please login to continue",
title: "Not logged in",
buttons:
{
success:
{
label: "Log in",
className: "btn-success",
callback: function()
{
$('.bootbox').modal('hide');
}
}
}
});
return false;
}
}
});
}, 5000);
});
PHP
require("config/db.php");
session_start();
include("config/session.php");
if(empty($session))
{
echo "sessionExpired";
}
I tried the above code is working, but after logout the modal show multipe until I refresh the page. I just want the modal show 1 time.
Use setTimeOut function instead of setInterval

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() {}
}
});
}

jQuery fileDownload conflicting with another jQuery plugin

I have two different jquery plugins loaded, one is UI related which allows me to display message popups and the other is the ajax fileDownload plugin. They both work fine. However, when I seem to run one function, it then starts conflicting with the other function.
I have a function called Export which initiates the fileDownload ajax request when a button is clicked. But then after the fileDownload is over, if I click on the button that launches the ExitAlert function, I end up getting the fileDownload re-initialising with the exit message. Below are the two functions.
Any idea what is going wrong?
Thanks
function Export() {
$("#Form").submit(function (e) {
e.preventDefault();
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
});
}
function ExitAlert() {
$("#Form").submit(function (e) {
e.preventDefault();
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
});
}
I seemed to have got it to work by changing the e.preventDefault and the functions now look like this (seems to work now):
function Export() {
$("form").submit(function (e) {
e.preventDefault();
});
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
}
function ExitAlert() {
$("form").submit(function (e) {
e.preventDefault();
});
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
}

Categories

Resources