Jquery: Redirect Page

Question!
$.ajax({
    type: "POST", 
    url: "http://localhost:8080/ChecktToken",
    data: {"token": ($.cookie("uid")) },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: false,
    success: function() {


    },
    error: function(data) {
        location.href =('login.html')   
    },
}); 

The above Ajax call is used for redirecting the user to the login page if he is trying to access any other pages before actually logging into an application. This works completely OK, but it takes about 2 seconds to redirect to the login page.

So for example if I try to access http://localhost:8080/index.html prior to logging in I will be able to see that page for 2 seconds before actually being redirected. Is location.href =('login.html') the best method for redirection or is there something better I could do?

Looking for advices.



Answers
2 second delay in redirecting page is due to Ajax call waiting for response from server. These 2 seconds may increase if network of server slows down. To prevent page load you have hide page till you get the response or error. You can do that using beforeSend call back in ajax.

  $.ajax({
    type: "POST", 
    url: "http://localhost:8080/ChecktToken",
    data: {"token": ($.cookie("uid")) },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: false,
      beforeSend: function() {
       //Hide page till you get the response. You can use element Id which holds entire body.
       $(body).hide();
    },
    success: function() {
      $(body).show();
    },
   error: function(data) {
      location.href =('login.html')   
    },
}); 
By : Anand G


This video can help you solving your question :)
By: admin