0

I have a simple function that retrieves a setting from cakephp core using ajax. But returning this value gives back undefined. I have been looking at the code and searching the web on what I am doing wrong, but I still do not seem to see it. It's probably cuz of my long working day that I am overlooking something stupid. Maybe you guys can help me clear up my mind here... What goes wrong is mentioned in the comments of below code:

$(document).ready( function() {
    // check session timeout setting from cakephp core
    var checkTimeoutSetting = function() {
        $.ajax({
            url: '/users/checktimeout',
            type: "POST",
            success: function (data, textStatus, jqXHR) {
                // data is logged as 60 on page load
                console.log(data);
                return data;
            }
        });
    };
    var sessiontimeout = checkTimeoutSetting();
    console.log('session: '+sessiontimeout);
    // sessiontimeout seems undefined now :(
    $("#remaining-session-time").html(sessiontimeout);
});

Also tried this with making sessiontimeout a global variable, but still gives the same undefined message in my console.log

Alvin Bakker
  • 1,456
  • 21
  • 40
  • Or should the response be in json format here? – Alvin Bakker Feb 05 '15 at 21:07
  • AJAX is **asynchronous** - you need to use a callback! That call is still processing when you try and use the `sessiontimeout` var – tymeJV Feb 05 '15 at 21:07
  • You can't return the result from an asynchronous function call. Your function finishes and returns long before the success callback is called. See the question this is marked a dup of for options on how to do this correctly. The crux of all the solutions is that you have to consume the result in the success handler either by operating on it their or calling another function from there and passing it the data. Returning a value from an async callback does not do anything useful. It just returns the value into the internals of the ajax engine. Your main function has already finished by then. – jfriend00 Feb 05 '15 at 21:10

0 Answers0