0

What's the best way to have a JS function to do a simple AJAX true/false request and return that result.

I want to do a simple AJAX request, in a JS function, that checks if a users session is still active. The function should wait for the AJAX request to complete and return true or false.

I've achieved this using a setInterval but I don't think this is the best way. I tried to use jQuery $.when but I couldn't get the function to return a result.

function checkSessionIsStillActive(){
    var result; //ajax result will be put in here. It will be undefined until ajax complete

    $.getJSON('application/app_cfc/session_check.cfm/ajax')
    .done(function( data ) {
        // return the value
        result = data.session_active;
    }); 

    // Do an interval loop check until the result is defined
    var interval_check = setInterval(function(){        
        // Return the result as soon as we have it
        if(result != undefined ){

            // Clear this interval loop
            clearInterval(interval_check);
            // return the result to the calling function
            return result;
        }
    }, 100);
}
IanOSullivan
  • 549
  • 1
  • 4
  • 12

2 Answers2

1

You should read about async javascript, especially Promise.

function checkSessionIsStillActive(){
    return new Promise((resolve, reject) => {
        $.getJSON('application/app_cfc/session_check.cfm/ajax')
            .done(data => {
                // return the value
                result = data.session_active;
                resolve(result);
            }); 
    });
}

If you call the function you would then do

checkSessionIsStillActive().then(data => {
    // result from function is available here
});
mind
  • 432
  • 6
  • 18
1

Use fetch() API and ASYNC code.

async function isSessionActive(url) {
   let data = await fetch(url);
   let jsonData = await data.json();
   jsonData.sessionActive ? true : false;
}

let result = isSessionActive('application/app_cfc/session_check.cfm/ajax');
console.log(result) // either true or false
Bryan Enid
  • 414
  • 3
  • 12