How to treat a "redirect" after an Ajax call with Jquery?

Asked

Viewed 2,791 times

3

Use Jquery to make an Ajax (GET) call. When "redirect" occurs, code 302, for a valid answer Jquery returns error instead of redirecting to the new URL. There’s some other way to treat it?

  • This happens when the session expires and redirects to the login?

  • 1

    @Rafaelmarcos in my case is not a login, but the content responds with code 302 Temporarily moved, I think that’s what’s giving the problem to do the treatment.

  • The browser should handle redirect automatically... Is this not happening? Or is the problem time to treat the answer redirect? Try using a get simple (without specifying format) and use callback then (or complete, if it is an older version of jQuery) and see what happens.

  • 1

    The simple fact of redirecting with status 302 should not give error, unless you try to access something that is in different format.

  • 1

    I found that I needed to define the variable Access-Control-Allow-Origin: ""* in the response header of my web server, even with the 302 status worked now.

2 answers

2


In my case, when I redirect to the Asp.net login, I add the following header to the login page reply:

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

          }
    });

This way, Ajax knows when the requested page was redirected to login, when the session expires.

  • I got it! You poison the response header with the LOGIN variable.

  • Just add some information to make Ajax easier.

2

Ajax in jQuery has 3 calbacks that can be used for what you want complete, Success and error, you could use both the complete as to the error to make that check. Take 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 http://api.jquery.com/jQuery.ajax/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.