a coder
a coder

Reputation: 7639

Can this old-style ajax call be easily done with jquery?

I'm working with some pretty old code and the following is being used to monitor session status. If the user is inactive for X minutes (determined by check_session.php), they are logged out.

The server side stuff works fine. Actually, the existing javascript appears to work OK as well, but looks like it needs cleaning up.

Here's the existing javascript:

function checkSessionStatus() 
{ 
    session_http.open('GET', '/check_session.php', true); 
    session_http.onreadystatechange = handleSessionHttpResponse; 
    session_http.send(null); 
}

function handleSessionHttpResponse() 
{ 
    if (session_http.readyState == 4) 
    { 
        results = session_http.responseText; 
        if (results == 'inactive') 
        {
            window.location='/logout.php';
            document.getElementById('session_divbox').innerHTML = results; 
        }
    }
}

function get_session_HTTPObject() 
{
    var xml_session_http; 
    if (!xml_session_http && typeof XMLHttpRequest != 'undefined') 
    { 
        try 
        { 
            xml_session_http = new XMLHttpRequest(); 
        } 

        catch (e) 
        { 
            xml_session_http = false; 
        } 
    } 
    return xml_session_http; 
} 
var session_http = get_session_HTTPObject(); 

function init_page_header() 
{
    window.setInterval( 'checkSessionStatus();',  30000);
}

This seems incredibly long for what it is doing.

I am still learning jquery and am able to do some basic ajax calls like this one, which places a returned value in a div:

$(document).ready(function() 
{
    $('#users_online').load('/show_users_online.php');
    var refreshId = setInterval(function() 
    {
        $('#users_online').load('/show_users_online.php');
    }, 2000);
    $.ajaxSetup({ cache: false });
});

The issue with the first bit of code is that it returns a value of 'inactive', which is then acted on by the client (window redirect).

Is it possible to do this in Jquery without winding up with dozens of lines of code? I may already know how to do this and am not seeing the forest for the trees -- some guidance here is appreciated.

Upvotes: 1

Views: 208

Answers (1)

jAndy
jAndy

Reputation: 236022

Even if its very vampiric question style, should look like

$.get('/check_session.php', function( data ) {
    if( data === 'inactive' ) { 
        window.location='/logout.php';
        document.getElementById('session_divbox').innerHTML = data;
    }
});

Upvotes: 2

Related Questions