Can an ajax call trigger the renewal of an ASP.NET session?

Currently tackling a timeout detection issue in an asp.net project. I've implemented an ajax function that checks every 5 seconds to determine if the session has expired. Interestingly, without the ajax function running, the session actually times out after a minute. However, with the function active, it continuously sends an "active" status. This makes me question whether my ajax function is responsible for keeping the session alive?

Ajax function:

             function isSessionAlive(){
                await jQuery.ajax({
                type: "POST",
                url: 'coolpage.aspx/hello',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    console.info("status: ", response);
                },
                failure: function (response) {
                    console.info("status: ", response);
                },
                cache:false
            });}

Asp.net page method

    //[WebMethod(EnableSession = true)]
    [WebMethod]
    public static string hello()
    {
        //return (HttpContext.Current.Session["dummy"] == null) ? "expired" : "active";

        if (HttpContext.Current.Session != null)
        {
            if (HttpContext.Current.Session.IsNewSession)
            {
                string cookieHeader = HttpContext.Current.Request.Headers["Cookie"];
                if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    return "expired";
                }
            }
        }

        return "active";

        // return HttpContext.Current.User.Identity.IsAuthenticated ?  "active":"expired";

    }

Answer №1

To make an asynchronous call in ajax, you need to utilize the setInterval function.

setInterval(function(){
   $.get('awesomepage.php/greetings');
}, 300000); // 5 minutes

Answer №2

In the event that your session has timed out, be sure to invalidate the session and display "expired". Make sure to verify the session value with an if/else statement after making an ajax call in the document.ready function.

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

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

Storing/retrieving data from a database using CSV files in C#

Can a CSV file be saved to a SQL Server Database table using C#? Is it necessary to convert the CSV file to Binary format for this process? Are there other alternatives, such as saving it in text format (since CSV is essentially a txt file)? It would be ...

Next.js pages do not respond to event listeners

Something strange is happening in my Next.js project. I've implemented a header that changes color as the page scrolls using the useEffect hook: The hook in the Header component looks like this: React.useEffect(() => { window.addEventListener(&a ...

Bring in solely the static variable from an ES6 module

I have a file called common.js which holds all the necessary variables and methods used in my App, including a nav-bar module (nav-bar.js) among others. Typically, every module in my app will import the entire common.js module, except for the login module ...

The comparison between 'MutableRefObject<string | null>' and 'string' will never be true, as they do not share any common types. Error code: TS2367

Struggling with a React and TypeScript issue I have stored the email and password in state variables const emailRef = useRef<string | null>(null); const passwordRef = useRef<string | null>(null); This is how I set them: const onEmailChange = ...

Validation of a multi-step form ensures that each step is filled out

I'm completely new to Angular and I'm attempting to implement validation in my form. The form structure was not created by me and is as follows: <div> <div ng-switch="step"> <div ng-switch-when="1"> < ...

The jQuery autocomplete feature presents all choices regardless of what is typed into the input field

I'm currently working on a jQuery script that retrieves a JSON response and creates individual "player" objects based on the data received. These player objects are then added to the availablePlayers array, which serves as the data source for the aut ...

Sending information from a mobile app (specifically, iPhone and Android) to an ASP.NET web application

Is it possible to transfer data from a mobile phone application (iPhone app / Android app) to an ASP.NET website application? Is there a need for a secure channel like SSL? For the ASP.NET website, I am considering using a WCF service to receive data fro ...

Link directly to a specific slide within the JQuery Revolution Slider

I have integrated the JQuery revolution slider into my website and it's working well. However, I am looking for some guidance on how to link to a specific slide within the slider. My goal is to have the slider scroll to a particular slide when a user ...

Exploring the Contents of IEnumerators

Curiosity led me to attempt decompiling my project's code. I grabbed the Assembly .dll file and utilized ILSpy for the decompilation process. Everything seemed to be functioning as expected, except for the IEnumerator<> methods in question. IEn ...

Ways to update status in intervals of x seconds

I am trying to update the name of every avatar automatically every X seconds. I found a helpful solution that works well, but currently it is displaying the same name for all avatars from the RandomAcidName array. I believe I need to iterate through this ...

Transform a series of image files into one cohesive video file

Similar Question: Converting bitmaps to avi file in C# .Net I have an interesting challenge of converting a series of image files into a single video file. I am using dotnet as my platform. I'm not sure where to start. Also, I would like to inclu ...

Tips for retrieving all error messages within a script tag using Vee Validate Version 4 in Vue 3

I am currently working with Vue 3 and vee-validate V4, but I'm facing an issue where I can't retrieve all error messages within the script tag. Is there a way to access all error messages from the script tag? <Form v-slot="{ errors }" ...

React Native query: What could be causing the inability to pass parameters (props) to my screen when utilizing stack navigator?

App.js const Stack = createNativeStackNavigator(); export default function App() { return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator initialRouteName="Main"> <Stack.Screen ...

My month sorting function is designed to work efficiently, although it seems to only be effective on the first

I am currently using a combination of JavaScript and Angular to sort through my data. Initially, I attempted to filter the data by month and it worked as expected the first time. However, for some reason, it stopped functioning properly afterwards, causing ...

How to Trigger a Child Component Function from a Parent Component in React.js

I want to trigger a function in my child component when a button is clicked in the parent component. Parent Component: class Parent extends Component{ constructor(props){ super(props); this.state = { //.. } } ...

"Discover the best way to use Ajax to submit a form once it has been successfully

Whenever I try to use Ajax to submit my form, I encounter an issue. If I use the click event instead of submit in the jQuery part, it works but the form doesn't validate. However, when I use submit, the Ajax doesn't trigger after validation. What ...

adjusting the vertical axis scale on the Google Charts API

During my experimentation with setting the vertical axis scale in Google charts, I found that the automatic scaling was not satisfactory for comparing two results. I wanted both results to be on an equal scale for a fair comparison. Despite setting the ma ...

There seems to be an issue with Bootstrap: the property this._config is

Here is the button I have: <button class="kv_styleclass_0 btn btn-outline-success btn-lg" data-bs-toggle="modal" data-bs-target="formModal" type="button"> Become a participant </button ...

I tried setting ajax async to false, but it doesn't seem to be functioning

I've been attempting to retrieve JSON data from another domain, and my code looks like this: var token = ''; function fetchData(){ console.log("Data fetched successfully"); for (var i=0; i < urls.length; i++){ var endpoint = &ap ...