Detect or block redirect with ajax?

8

I'm having a problem with an ajax request I'm making.

The requested url is a url x , but when I make the request, it redirects me to a url y .

I'm using the $.ajax function of jQuery.

I would like to know if you can detect by jQuery that the requested url has been redirected. Or stop this redirect by reporting an error.

As the redirection does not count as an error, it is giving a problem in the way I treat the data, that is, even with the redirection, the request calls the success .

    
asked by anonymous 07.12.2015 / 14:51

2 answers

9

I can not provide a detailed response now, but I can say that it is impossible to detect in Ajax or normal requests the redirection, the only one that knows that there was redirection is the interface of the browser's internal requests.

It would be something like:

  • UserInterface:

    Itistherenderedlayer,whereyoualreadyhavethereadyorpartialresponse,thebrowserscreen(knownaswebView)

  • Requestsandresponsesinterface:

    ItisaninternalinterfacethatonlyrespondstothebrowserandmanagesallHTTPrequests,isresponsibleforsolvingaserver,sendingtherequesttoitandpickinguptheresponse,incaseofredirectionitsendsanewrequest.

  • HTTPServer:

    Itisasite,domain,localornot,whichisaccessiblethroughanaddressanditsanswersareheadersfollowedbytextsorbinarydatathat"do nothing" (since the responsible for interpreting this is the interface of requests and responses) .

When a redirect occurs with 301 , 302 , etc., who will manage this is the Request and Answer Interface , the only tool that sees this is the browser debugger press the F12 keypad that will display the debug).

How to solve

The only way is to change the approach, ie instead of redirecting in the back end, switch to the front end and do something similar to what you put in your own response, json or xml responses with "commands" that say what to do and even create your own custom error codes, like this:

  • Error code example (HTTP response will always be 200 Ok )

    { "status": 5000, "message": "Erro na requisição" }
    
  • Success code example

    { "status": 1000, "message": "Cadastrado com sucesso" }
    
  • Sample redirect code on the front end

    { "status": 9000, "message": null, "url": "/path/route" }
    

The code would look something like:

var request = $.ajax({
  url: "/route/page",
  method: "GET",
  data: { id : 1 },
  dataType: "json"
});

request.done(function(data) {
     if (data.status === 9000) {//Detecta redirecionamento
        window.location = data.url; //Redireciona (se quiser :) )
     } else {
        //...Código segue fluxo normal
     }
});

request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});
  

Note: I think that maybe you have thought about making a request on the server, it would work, but I think that besides being more of a gambiarra, it would be very costly for the server as the number of users increased accessing at the same time

    
07.12.2015 / 19:19
1

I went behind a font to see if I could solve not only my problem.

Every redirect usually returns as a response code 301 and 302 . When the answer returns correct the status is 200 .

I'm talking to understand what I found in this answer no SOEN.

  

In fact, you do not have the ability to detect whether a 302   it occurred. If redirect 302 leads to a 200, then your program   acts as if the original request led directly to   200.

That is, ajax is "cheated", so to speak, by a redirect, acting as if the redirect were expected behavior to return success in the XHTTPRequest request.

The maximum that can be done in this case is: If you request a url x expecting to receive json data for example, and it is redirected to a y url, as is my case, you can handle this by checking found the data expected by json in your successful ajax request call.

Example:

URL X

 {"message":"Cadastrado com sucesso"}

URL Y is the home page for my application

AJAX Request

$.ajax({
     url: '/x',
     success: function (response)
     {
           if (response.message) {
               return alert('Dados esperados foram retornados');
           }

           alert('Ocorreu um erro! Dados incosistentes')
     }
})
    
07.12.2015 / 15:59