There doesn’t seem to be a clear solution to creating a page redirect when a session expires using AJAX when doing a web search.
All server request invoked with AJAX will use XHR (XMLHttpRequest) whether done using XML, plain text, or JSON. There is also an easy way to capture the server response when the session expires. It doesn’t matter if you’re using jQuery, MooTools, or writing your own custom javascript.
Here’s some PHP code as a simple function:
1 2 3 4 5 6 7 8 9 10 11 12 | function redirect($url, $permanent=false, $statusCode=303) { if($_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest"){ echo "<script>window.top.location.href='$url'</script>"; }else{ if(!headers_sent()) { header('location: '.$url, $permanent, $statusCode); } else { echo "<script>location.href='$url'</script>"; } exit(0); } } |
If you’re using a framework like codeigniter, simply create a helper file and autoload it. There are so many people complicating this with additional javascript. Now you can invoke this inside any controller by redirecting (303) back to the homepage or login page.
Or, just add the above code to your own custom PHP file and call it using:
1 | ajax_redirect('http://www.domain.com'); |