jQuery PHP Ajax Check User Logged in show modal - javascript

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

Related

Set isConfirmed to true after timer runs out on SweetAlert2

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.

Javascript modal auto close after message

I am using below java script for contact form submission & after particular time the modal should be closed automatically
if ($('.js-form').length) {
$('.js-form').each(function() {
$(this).validate({
errorClass: 'error form-error',
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "mail.php",
data: $(form).serialize(),
success: function() {
$('#error').modal('hide');
$('#success').modal('show');
},
error: function() {
$('#success').modal('hide');
$('#error').modal('show');
}
});
}
});
});
}
You need to return false at the end of submission of your form.
You could use setTimeout() inside the handlers like this.
success: function() {
$('#error').modal('hide');
$('#success').modal('show');
setTimeout(function(){
$('#success').modal('hide');
}, 3000);
},
error: function() {
$('#success').modal('hide');
$('#error').modal('show');
setTimeout(function(){
$('#error').modal('hide');
}, 3000);
}
To close after a particular time, you have to use setTimeOut. with your current code, the hide/show functionality will execute immediately after the ajax response.

Wait for Bootbox Confirm to Run Ajax

I need to run an ajax function after confirm is pressed on a bootbox confirm modal. The modal flashes briefly, then the php code is run without waiting. How do I make it wait.
My Javascript runs when I remove the bootbox but I want to confirm before it's run
My code is,
$('#change_pass_form').submit(function () {
bootbox.confirm({
message: "Your password is about to be changed. Are you sure?",
buttons: {
cancel: {label: '<i class="fa fa-times"></i> Cancel'},
confirm: {label: '<i class="fa fa-check"></i> Confirm'}
},
callback: function (result) {
if (result === 'true') {
$.ajax({
type: 'POST',
url: 'php_files/profile_php_files/profile_password_change_process.php',
data: {
user_id: sessionStorage.getItem('user_id'),
new_password: $('#new_password').val(),
repeat_password: $('#repeat_password').val()
},
success: function (data) {
if (data === 'correct') {
bootbox.alert({
size: 'small',
message: 'Your password has been changed. You will now be logged out.',
callback: function () {
window.location.replace('index.html');
}
});
return true;
} else {
bootbox.alert({
size: 'small',
message: data
});
return false;
}
}
});
} else {
return false;
}
}
});
});
All of the return false and return true are returning to callbacks and not to the outer submit handler function. Also, they occur only after asynchronous events so the default submit process is never prevented.
Just prevent the default browser submit
$('#change_pass_form').submit(function (event) {
event.preventDefault();

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