Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle session timeout when loading data through ajax with jquery DataTables

My application is behind a sign in, so when loading the data through ajax, I need to verify the user still has an active session. If the user does not have an active session, I return back with echo json_encode(array('TIMEOUT')); which outputs ["TIMEOUT"]. How do I read that response and send the user back to the sign in page?

In previous versions of DataTables, I was able to do the following:

"fnServerData": function ( sSource, aoData, fnCallback, result ) {
                            $.getJSON( sSource, aoData, function (json) { 
                              if(json == "TIMEOUT")
                              {
                                window.top.location.href = "/sign_out?action=to";
                                return;
                              }

                              fnCallback(json)
                            } );

Under DataTables 1.10, fnServerData has been replaced by ajax (see docs and ajax.data). How do I accomplish the same thing with the new DataTables version? I feel like I am close, but it just isn't working...possible because I am doing something wrong attempting to parse the response (I never hit inside the if statement).

"ajax": {
        "url": "/account/location_load",
        "data": function (myJson) { 
            if(myJson == "TIMEOUT")
            {
              window.top.location.href = "/sign_out?action=to";
              return;
            }

            return myJson;
          }
      }
like image 320
justanotherprogrammer Avatar asked Jan 19 '26 05:01

justanotherprogrammer


1 Answers

After a day and a half working on it, I finally found a working solution using ajax.dataSrc (doc)

"ajax": {
        "url": "/account/location_load",
        "dataSrc": function (myJson) {

            if(myJson == "TIMEOUT")
            { 
              window.top.location.href = "/sign_out?action=to";
              return "";
            }

            return myJson.data;
          }

I don't know why this version allowed me to read myJson and the other didn't, but it works. The working PHP code ended up being echo json_encode('TIMEOUT');

like image 69
justanotherprogrammer Avatar answered Jan 20 '26 19:01

justanotherprogrammer