Handle session timeout when loading data through ajax with jquery DataTables

datatables, datatables-1.10, jquery, php

Solution

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');`

Problem

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; } } ```

Original source