Anuja P
Anuja P

Reputation: 2143

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.

Upvotes: 3

Views: 1107

Answers (5)

Navneet Singh Chouhan
Navneet Singh Chouhan

Reputation: 42

use ajaxComplete event.

$( document ).ajaxComplete(function() { 
  window.location.href = "/login";
});

Upvotes: 0

Anuja P
Anuja P

Reputation: 2143

        /***
         * Global Ajax call which gets excuted before each $.ajax and $.post function
         * at server side chk session is set or destroy 
         ***/
        $(document).on('ajaxStart', function()
        {
            $.post( BASEURL+"/login/chkLogin",
            {},
            function(data)
            {
                if (data == 'login') {
                  window.location = BASE_URL+'/login'; //Load the login page
                }
                else
                {
                    //alert('all okay! go and execute!'); 
                    //No need to write anything in else part 
                    //or can say no need of else block 
                    //if all okay normal ajax action is processed
                }
            });     
      });

This is what I want. working perfectly for my functionality. Thank you for all answers and comments. I got a big reference from you.

Upvotes: 0

Maha
Maha

Reputation: 66

This code can solve your problem.

$(document).bind("ajaxSend", function(){
   //DO Someting..
});

Note beforeSend is local event and ajaxSend is global event

Upvotes: 2

dfsq
dfsq

Reputation: 193261

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

Upvotes: 3

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/

Upvotes: 3

Related Questions