Organizational Research By

Surprising Reserch Topic

How to manage a redirect request after a jQuery Ajax call



asked May 20, 2015 in JAVASCRIPT by rahulgii
0 votes
26 views



Related Hot Questions

3 Answers

0 votes

I solved this issue by:

  1. Adding a custom header to the response:

    public ActionResult Index(){
        if (!HttpContext.User.Identity.IsAuthenticated)
        {
            HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
        }
        return View();
    }
  2. Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:

    $(document).ajaxSuccess(function(event, request, settings) {
        if (request.getResponseHeader('REQUIRES_AUTH') === '1') {
           window.location = '/';
        }
    });
answered May 20, 2015 by rahulgii
0 votes

The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.

For example, our wrapper function was something like:

 


    function cbWrapper(data, funct){
    	if($("#myForm", data).size() > 0)
    		top.location.href="login.htm";//redirection
    	else
    		funct(data);
    }
    

 

Then, when making the Ajax call we used something like:

 


    $.post("myAjaxHandler", 
    	   {
    		param1: foo,
    		param2: bar
    	   },
    	   function(data){
    		   cbWrapper(data, myActualCB);
    	   }, 
    	   "html");
    

 

This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.

answered May 20, 2015 by rahulgii
0 votes

se the low-level $.ajax() call:

$.ajax({
  url: "/yourservlet",
  data: { },
  complete: function(xmlHttp) {
    // xmlHttp is a XMLHttpRquest object
    alert(xmlHttp.status);
  }
});

Try this for a redirect:

if (xmlHttp.code != 200) {
  top.location.href = '/some/other/page';
}

 

answered May 20, 2015 by rahulgii

...