AJAX function to detect when session is expired and log out - javascript

I have this function that checks if a session in the current tab has expired. However, if I open another tab and log out through there, my current tab won't know and somehow it maintains its session until I access an item from the navigation menu. Is there a way I can improve this by detecting when a user has either logged out or if the users session has expired?
The main issue right now is if they open another tab and just log out from there.
function check_if_logged_in(){
$.ajax({
method: "POST",
url: "<?php echo site_url('Common/CheckSession'); ?>",
beforeSend: function () {
$('.loading').show();
},
success: function(data){
if(data==="undefined"||data===null||data===0){
console.log("logged out");
// window.location.replace("<?php // echo BASE_URL;?>");
}else{
console.log("logged in");
}
$('.loading').fadeOut("slow");
},
});
}
This is my checkSession function
public function checkSession(){
if($this->logged_in()===false){
echo false;
}else{
echo true;
}
}
this->logged_in() just checks if the session is still active.
I have read about LocalStorage by HTML5. I'm wondering if this will affect mobile devices as the site itself is responsive and I've heard that iOS or some devices don't support LocalStorage.

You should write a js function which can be accessed in every file. Most probably in your footer.
Then write the below code which will be called at an interval of every 5 seconds(You can change it according to your convinience).
$( document ).ready(function() {
setInterval(function () {
checkSession();
}, 5000);
});
function checkSession()
{
$.ajax({
type: "POST",
url: "your_session_checking_function",
success: function (data) {
data = JSON.parse(data);
if(data.response != "true")
{
window.location.href = 'redirect to login page';
}
}
});
}
Then according to the result obtained in ajax success you can redirect it to the login page.

Related

AJAX won't load new page content without page refresh

I executed an AJAX request to load content into my page. Here's the function I created for this request:
function displayForums() {
var session = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/display_forums.php',
data: 'POST',
data: {session: session},
success: function(data) {
console.log("display successful");
$(data).appendTo("#forums-container");
}
});
}
Then, I call this function I just declared (displayForums()) when the document loads:
$(document).ready(function() {
displayForums();
});
Finally, I have an AJAX call that submits user input from a form into a database.
$("#start-thread-form").on("submit", function(e) {
e.preventDefault();
var forum_title = $("#start-thread-form input").val();
var forum_message = $("#start-thread-form textarea").val();
var id = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/insert_forums.php',
type: 'POST',
data: {forum_title: forum_title, forum_message: forum_message, id: id},
success: function(data) {
console.log(data);
$(".success-msg").append("Thread created successfully" + "<br>").show();
setTimeout(function() {
$(".success-msg").hide();
$(".success-msg").text('');
}, 2000);
$('input[type="text"],textarea').val('');
displayForums();
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
The problem is that when the AJAX call that inserts data into the database completes, the original AJAX call doesn't load the new data into the page unless I refresh the page. I tried placing the displayForums() function inside of the success function, but it didn't work. How can I adjust the AJAX calls to load the newly inserted data without refreshing the page?
You run your JavaScript when the submit event of a form fires.
The default behaviour of a form submission is to make an HTTP request to the action and load the response as a new page.
If you don't want the form to submit, then you have to stop it.
$("#start-thread-form").on("submit", function(event) {
event.preventDefault();
$(document).ready(displayForums());
this is WRONG, it should be:
$(document).ready(function() { displayForums() });

how can I trigger javascript css action?

I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>

Javascript - When a button is clicked, redirect to Login page if not authenticated

I inherited an MVC app with jQuery and Kendo. Most of the controller actions have the [Authorize] attribute and it handles the redirection to the Login page nicely if the user is not already authenticated.
However, there's one feature that requires some additional information before the action is invoked. So, when the button for that feature is clicked, a Kendo window is displayed asking the user for a DateTime input. Then the action is called with that extra piece of input data, and the user is sent to another page after the action completes with the result of that action.
Here's the simplified code flow:
btnClicked_Listener{
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new { date = [DateTime input] })
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
This works fine if the user is already logged in. But if the user is not already logged in, here's what happens:
Kendo window popups for DateTime input.
Login page is displayed (since MyAction1 has the [Authorize] attribute).
User logs in.
Page '/MyController/MyAction2?planId=' is invalid, since MyAction1 never gets hit, and so result=null.
How can I fix this where the Javascript code can detect whether the user is logged in or not, and direct him to the Login page instead?
I do not want to hide the button if the user is not authenticated. I want to let the user be able to click on the button, but get redirected instead.
Thanks for any help!
You can mix server side code and javascript code to checking weather user is logged in or not.
<script>
btnClicked_Listener
{
#if (User.Identity.IsAuthenticated)
{
<text>
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
</text>
}
else
{
<text> window.location.href = 'Login page url' </text>
}
}
</script>
Edit: If you want pus your JS code in external file you have to put your code inside a function then pass a bool value to the function which indicate whether user is authenticated or not.
External JS
function handleButtonClick(isAuthenticated) {
btnClicked_Listener
{
if (isAuthenticated) {
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function(result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function(xhr, error, message) {
handleError(xhr, error, message);
}
});
} else {
window.location.href = 'Login page url';
}
}
}
and inside your html page call that function:
<script>
$(function() {
handleButtonClick(#User.Identity.IsAuthenticated);
});
</script>

jQuery AJAX post to PHP everytime a click is fired off

I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!
on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps
Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

A callback for a page refresh function

Is there any way to implement a callback for a page refresh function, check if the page is ready after it is refreshed and then print a message? I'd like to show refresh the page and show a certain message after clicking a button, however, I need to stay within my code in order to know what message to show. Anything similar to the next code would be great:
location.reload(function(){
alert ('done refreshing and document is ready');
});
On page reload, your JS application gets re-initialized and starts all over again, so you cannot have a callback.
However, what you can do is add a hash fragment to the URL before reloading.
window.location = window.location.href + "#refresh";
window.location.reload();
Then, on page load, check if the hash fragment exists. If it does, you'll know you just refreshed the page.
If you want to user window.location.reload() you have to use Browser's sessionStorage. Here is my code, I use this for saving data.
window.onload = function () {
var msg = sessionStorage.getItem("nameShah");
if (msg == "Success") {
sessionStorage.setItem("nameShah", "");
alert("Saved Successfully");
}
}
$("#save").click(function () {
$.ajax({
url: "/AspNetUsers/SaveData",
type: "POST",
async: true,
data:{userName: "a"},
success: function (data) {
if (data.Msg == "Success") {
sessionStorage.setItem("nameShah", "Success");
window.location.reload();
}
}
});
});
Server Side:
public ActionResult SaveData(string userName)
{
return Json(new { Msg = "Success" }, JsonRequestBehavior.AllowGet);
}
The way to go is using
$(document).ready(function(){
alert('done refreshing and document is ready');
});
But it doesn't differentiate a first load from a refresh. But you could achive that using sessions. For example, using PHP:
<?php
session_start();
$showJs = false;
if( !isset($_SESSION['loaded_before']) ) {
$showJs = true;
$_SESSION['loaded_before'] = true;
}
?>
...
<?php if($showjs) { ?>
<script type="text/javascript">
$(document).ready(function(){
alert('done refreshing and document is ready');
});
</script>
<?php } ?>
If you really want to go javascript side, you can use sessionStorage.varName before reloading, and then you check that var and continue.

Categories