Detect or block redirect with ajax?

Asked

Viewed 934 times

10

I’m trying a problem with an ajax requisition I’m doing.

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

I’m using the function $.ajax 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.

Since the redirect does not count as an error, it is giving problem in the way I handle the data, I mean, even with the redirect, the request calls the success.

  • 1

    Do you have any sample code, friend? It’s a little difficult to understand your scenario exactly

  • @Wallacemaxters, I believe it is not possible to detect if the server redirected your AJAX request, what can be done is to add a Header on the server informing the processed URL, so you compare this header with the sent url...

  • Our @Victoralencarsantos needs to be more specific? How do I demonstrate a code redirection? Everything I could explain is already in the question

  • One way to circumvent this is to send the ajax request to your own server. Then on the server side CURL would do the request. The logic in this is that CURL detects redirects. The problem is the consumption of data traffic and processes on the server just to do this. But anyway, if it’s something so important, there’s a functional gambit.

  • @Danielomine’s a good move. But in my case to do this would almost in the same, would be the system making request to the same system to then return to the client.

2 answers

10


I can’t provide a detailed answer right now, but I can say that is impossible detect in Ajax or normal requests the redirect, the only one who knows that there has been redirection is the interface of internal browser requests.

It would be something like:

Interface do navegador

  • User interface:

    It is the rendered layer, where you already have the ready or partial response, the browser screen (known as webView)

  • Request and response interface:

    It is an internal interface that responds only to the browser and manages all HTTP requests, is responsible for resolving a server, send the request to it and pick up the response, in case of redirection it sends a new request.

  • HTTP server:

    It is a website, domain, location or not that is accessible through an address and its responses are headers followed by texts or binary data that "do nothing" (because the responsible for interpreting this is the interface of requests and responses).

When a redirect occurs 301, 302, etc, who will manage this is the Request and response interface, the only tool that sees this is the browser debugger (in Chrome press the F12 keyboard 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 tell you what to do and even create your own custom error codes, thus:

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

    { "status": 5000, "message": "Erro na requisição" }
    
  • Example of success code

    { "status": 1000, "message": "Cadastrado com sucesso" }
    
  • Example of front-end redirect code

    { "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 maybe you were thinking of making a request on the server, it would work, but I think that besides being more of a gambiarra, it would be quite expensive for the server as it increased the number of users accessing at the same time

  • 1

    Never gambiarra in my code

  • @Wallacemaxters just my drawing that did not look good, but on the weekend I do a "more correct" :)

2

I went to find a source to see if I can solve not only my problem.

All redirect, usually back as response code 301 and 302. When the answer returns correct the status is 200.

I’m telling you to understand what I found in that reply in the SOEN.

In fact, you don’t have the ability to detect if a response 302 occurred. If 302 redirect leads to a 200, then your program acts in the same way as if the initial request led directly to a 200.

That is, ajax is "tricked", so to speak, by a redirect, acting as if the redirect is an expected behavior to return success in the Xhttprequest request.

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

Example:

URL X

 {"message":"Cadastrado com sucesso"}

Y URL is the home page of 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')
     }
})
  • what you posted is not the solution of the problem described by you.

  • No one is arguing, we are seeing the best solution.

  • You solved my problem.

  • 3

    It is not that ajax is tricked, it is that you missed (sorry the sincerity) you understand the Answer layer in the browsers, the browsers are receiving the answer at a deeper level and only deliver the screen the final answer. Ajax is nothing more than a normal request on a layer where javascript can control and set in variable response values. If you even notice in normal requests (without ajax) you will not be able to detect the redirect. What remains to understand is the http layer for the end user :)

  • The "get tricked" ajax was just a crude expression. I understand how the stops work (when we open the Chrome console you can see that the url is redirected 3 times). If ajax will get the final answer, then obviously, if no error occurs in the final answer, it will return ok

Browser other questions tagged

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