Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to call one javascript function before all ajax and jquery post function

I have various function with the ajax and $.post syntax which gives call to the server function. But when session gets expired and page is not refreshed my ajax code wont work. In this I want to redirect the page to login controller. As it this is ajax call my redirection code is not working.

Is there any code or JavaScript/jQuery function which gets executed before any other jquery ajax and post function.

I am using PHP(Yii framework) on server side.

Please let me know. Thank you.

like image 428
Anuja Patil Avatar asked Sep 13 '26 16:09

Anuja Patil


2 Answers

You can use the "beforeSend" ajax event where you can check you session and if it's expired you can do something else:

$.ajax({
   beforeSend: function(){
     // Handle the beforeSend event
   },
   complete: function(){
     // Handle the complete event
   }
   // ......
 });

Check this for more info: http://api.jquery.com/Ajax_Events/

like image 96
Rares - Alexandru Hutanu Avatar answered Sep 15 '26 07:09

Rares - Alexandru Hutanu


jQuery provides a set of AJAX events you can listen during request lifecycle. In your case you can subscribe to ajaxError event triggered on document to react when requests failed as unauthorized:

$(document).on('ajaxError', function(el, xhr) {
    if (xhr.status == 401) {
        alert('Unauthorized');
    }
});
like image 29
dfsq Avatar answered Sep 15 '26 06:09

dfsq