Rakesh Tholiya Rakesh Tholiya - 1 year ago 107
Ajax Question

Detect PHP session expired in jQuery AJAX response globally

I am implementing ajax based layout after login, I want to acheive functionality like detect session is expired or not in all ajax request which ie call automatically or call by any ajax function.
How can I detect in ajax response user session is expired or access ajax request after login.

Note: I need it globally, It may be requested from different url, different binded events, differnt functions it should be $.ajax(), $.get(). $.post(). $.load() or any ajax based jQuery function.

Thanks in advance

Answer Source

I have worked in same concept as you want to achieve. I achieved it as mentioned it below.

In PHP side code.

In server side code of PHP, you need to handle session for login where you allow access after login only. If user session not set or expired you need to set forbidden eror in response header.

header('HTTP/1.0 403 Forbidden');

If you using any PHP framwork all mazor frameworks provides throw execptions methods so you have to refere framwork document.

In Javascript side

For Global settings and global callback of AJAX in jQuery you can you $.ajaxSetup() function. Include it on you common javascript file which is used after login.

    error: function(xhr, status) {
            // write your code for redirect url or open login popup here.

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().

Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download