I am working on a project that uses user authentication. I ran into a problem with my AJAX requests if the request did not have an authenticated session.
I have a 3min session timeout, so if the user has been idle for 3 minutes, then do some action that triggers the AJAX request, then the request will fail and return error 403. Here, what I plan to do is intercept the entire AJAX request from the page and send the ping to the server, which will return a JSON object, indicating whether a valid session exists. If there is one, the client will continue the current request, otherwise it will reload the current page, which will lead the user to the login page, and the user must again provide credentials.
Here is my implementation.
$("#param-ajax").ajaxSend(function(evt, request, settings) { var pingurl = GtsJQuery.getContextPath() + '/ping.json'; var escapedurl = pingurl.replace(/\//g, "\\/"); var regexpr1 = eval('/^' + escapedurl + '\\?.*$/'); var regexpr2 = eval('/^' + escapedurl + '$/'); // Proceed with the ping only if the url is not the ping url else it will // cause recursive calls which will never end. if (!regexpr1.test(settings.url) && !regexpr2.test(settings.url)) { var timeout = false; $.ajax({ url : pingurl, cache : false, data : { url : settings.url }, async : false, complete : function(request, status) { if (status == "error") { try { // GtsJQuery.getJsonObject() converts the string // response to a JSON object var result = GtsJQuery .getJsonObject(request.responseText) if (result.timeout) { timeout = true; return; } } catch (e) { // ignore the error. This should never occure. } } } }); // Reload the window if there is a timeout -- means there is no valid // sesstion if (timeout) { window.location.reload(); } } });
Everything works fine here, including window.location.reload (), but the original ajax request is not interrupted. Because the original AJAX request is not interrupted after the page reload starts, the AJAX request is also sent to the server. I need some mechanism that will allow me to abort the original request if the timeout is correct.
This post offers some answer, but the problem remains with third-party plugins such as datatables, which uses AJAX. We cannot write an error handler for these AJAX requests.
Thanks.
source share