How to handle a "redirect" after an Ajax call with JQuery?

3

Use JQuery to make an Ajax call (GET). When "redirect" occurs, code 302, for a valid response the JQuery returns error instead of redirect to the new URL. Do you have any other way to handle this?

    
asked by anonymous 07.02.2014 / 19:39

2 answers

2

In my case, when I redirect to login in asp.net, I add the following header in the login page response:

Response.AddHeader("LOGIN", "LOGIN");

In the Javascript call, I make the following treatment:

    $.ajax({
        type: "POST",
        url: '/Pagina.aspx',
        data: dados,
        complete: function (XMLHttpRequest, textStatus) {

            if (XMLHttpRequest.getResponseHeader('LOGIN') != null)
                window.location.reload(); // Atualizo a pagina para redirecionar para o login

//Seu código

          }
    });

In this way, Ajax knows when the requested page has been redirected to the login when the session expires.

    
07.02.2014 / 19:58
2

The ajax in jQuery has 3 calbacks that can be used for what you want complete , success and error , you could use both complete and error to do this verification. See the example:

$.ajax({
    url:"http://fiddle.jshell.net/favicon.png",
    complete: function(data){
        // aqui você manipula os dados para agir de acordo com a resposta do ajax
    },
    success: function(data){
        // aqui você manipula os dados para agir de acordo com a resposta do ajax
    },
    error: function(data){
        // aqui você manipula os dados para agir de acordo com a resposta do ajax
    }
})

All other questions can be found in the documentation link

    
07.02.2014 / 20:55