Tips for activating a function right before a session timeout in ASP.NET

I'm currently working on implementing a feature that tracks user activity by recording check-ins and checkouts before their session expires. I have set up a session timeout to handle this but now I need to call a method using JavaScript and Ajax to run just before the session ends. However, when trying to execute the method, it isn't working as expected. Below is the code snippet:

Admin.Master.cs


     protected void Page_Load(object sender, EventArgs e)
            {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    if (!this.IsPostBack)
                    {
                        Session["Reset"] = true;
                        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
                        SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
                        int timeout = (int)section.Timeout.TotalMinutes * 1000 * 60;
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);
                    }
    }

 [WebMethod]
        public void logout_timeout() //This is the method I am attempting to run
        {
}

Admin.Master

<script type="text/javascript">
        function SessionExpireAlert(timeout)
        {
            debugger
            var seconds = timeout / 1000;
            document.getElementsByName("secondsIdle").innerHTML = seconds;
            document.getElementsByName("seconds").innerHTML = seconds;
            setInterval(function () {
                seconds--;
                document.getElementById("seconds").innerHTML = seconds;
                document.getElementById("secondsIdle").innerHTML = seconds;
            }, 1000);
            setTimeout(function ()
            {

                //Show Popup before 20 seconds of timeout.
                $.ajax({
                    type: "POST",
                    url: "Admin.Master/logout_timeout",
                    data: "{}",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: OnSuccess,
                    error: OnError
                });
                $find("mpeTimeout").show();
            }, timeout - 20 * 1000);
            setTimeout(function () {
                window.location = "Login.aspx";

                // Additional AJAX request example

                //$.ajax(
                //                  {
                //                      type: "POST",
                //                      contentType: "application/json; charset=utf-8",
                //                      url: "Case.aspx/removeTrans",
                //                      data: "{ 'DelData':'" + transId + "'}",
                //                      success: function (result) { window.location.reload(true); console.log("successful!"); }
                //                  })



            }, timeout);
        };

Answer №1

Relocate the logout_timeout function to xxxx.aspx and make a request to the Ajax URL "xxxx.aspx/logout_timeout" instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage TypeScript with AngularJS to validate interpolation and binding within HTML documents

While TypeScript can detect compile errors for *.ts files, the question arises if these benefits can be extended to AngularJS views/templates. Consider a scenario where the code snippet below is present: <div ng-controller="HomeController as home"> ...

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

Developing a custom directive that utilizes a dynamic ng-options configuration

Alright, let me share with you my personalized directive: angular.module('bulwarkWebControls', []) .directive('customDropdown', [ function() { return { scope: { label: '@', // can be om ...

Utilizing Discord.js to enable a command for a particular channel

Running a Discord.js bot and struggling to figure out how to restrict the command! help to only the #commands channel. Already have the channel ID, so what steps should be taken in the command event to achieve this? Appreciate any guidance! ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

Can you explain the meanings of ?. and ?? in JavaScript?

Can anyone explain the significance of ?. and ?? in the following code snippet? history.replace(location.state?.redirectPath ?? '/home') ...

The repeated problem persists in Ajax where PHP is producing inaccurate results

Every time I run this code, it keeps showing 0 even when the username and password are correct. I even tried running the PHP code without AJAX and it worked perfectly. PHP include('config/connection.php'); if(isset($_POST['login'])){ ...

What is the best way to include an external Javascript file from a different server?

Below is the Express code snippet I have for the GET method: const express = require('express'); const app = express(); app.get('/', function(req, res) { res.sendFile(path.join(__dirname, '../public/index.html')); }); app ...

Error in Vuex when attempting to modify a local version of the state leads to a mutation issue

I'm facing a perplexing issue in my Vue application that has left me puzzled. The error message I'm encountering when trying to update a local version of a state element reads as follows: Error: [vuex] Do not mutate vuex store state outside mu ...

The ins and outs of import and export output explained

I'm currently struggling to understand the output of Import/Export Statement. For example, if I were to write this code: import React, { Component } from 'react'; import Cperson from '../components/person/person.js'; console.log ...

Guide to creating and importing a JSON file in Wordpress

I'm looking to save a list in a JSON file within the Wordpress functions.php file. Can you guide me on how to achieve this? function ScheduleDeletion(){ ?> <script type="text/javascript"> var day = (new Date).get ...

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

Is there a way for me to include a prefix in the path where Vue pulls its component chunks from?

I recently incorporated VueRouter into my project and encountered an issue with the asset URL not being correct. Instead of displaying www.example.com/js/0.main.js The URL it generates is www.example.com/0.main.js Any suggestions on how to include the ...

Incorporate the "Enhanced WMD Editor" into textareas that are dynamically loaded through AJAX forms

Our team is currently integrating Stackoverflow's WMD / Markdown editor into a Symfony project. We have managed to successfully implement it on textareas that do not involve any AJAX. However, we are facing challenges when we need to load the textarea ...

What is the best way to display JSON response data in a datatable by utilizing jQuery AJAX requests?

I am attempting to implement a date range search using jQuery Ajax and display the data in a datatable. Below is the PHP controller code I am using. public function date() { $date_from = date('Y-m-d H:i:s', strtotime($this->input->pos ...

Adding Conditionally Specified Properties to a Parameterized TypeScript Interface Based on Type

Encountering a challenge with TypeScript where I need to selectively add properties to a generic interface depending on the type parameter. Let me explain further with an example: Consider two interfaces, A and G<T>: interface A { IA: string; } ...

How can I efficiently load multiple database divs asynchronously?

Utilizing ajax and jQuery, my goal is to automatically refresh certain divs every 5 minutes with values retrieved from a database. For instance: <div id="1">One</div> <div id="2">Two</div> <div id="3">Three</div> &l ...