Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the final URL after an Ajax redirect?

Tags:

jquery

ajax

I am working on an AJAX script that makes a GET request to a shortened URL, like a bit.ly link. How do I actually get the URL of the final/redirected page?

I can get the response headers from the redirected page, but it doesn't appear to contain the URL information:

$.ajax({
  url: "http://www.thislinkredirects.com",
  success: function(data, status, xhr) {
    var response = $(data);
  },
  complete: function(xhr) {
    console.log(xhr.getAllResponseHeaders());
  }
});

Result:

Date: Tue, 23 Jun 2015 03:22:07 GMT
Allow: POST, GET, OPTIONS, PUT, DELETE
Server: lighttpd/1.4.35
X-Powered-By: PHP/5.3.3
Transfer-Encoding: chunked
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Content-type: text/html
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: accept, authorization

I do not have control of the server making the get request.

like image 935
docta_faustus Avatar asked Jun 23 '15 03:06

docta_faustus


People also ask

Does ajax follow redirect?

ajax appears to always follow redirects.

What does an ajax call return?

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.

What is the URL parameter in ajax?

The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .

Is ajax get or POST?

GET vs POST in AJAX calls Unless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data).


1 Answers

As I answered a similar question here: https://stackoverflow.com/a/48445360/1398908

A better solution is to supply jQuery's ajax with a custom xhr object like this:

var xhr = new XMLHttpRequest();

$.ajax({
    url: '/url',
    type: 'post',
    data: '...',
    xhr: function() {
         return xhr;
    }
});

Then you can access the current URL in any callback

success: function () {
    console.log(xhr.responseURL);
}

Note: IE doesn't support the responseURL property. (See docs)

like image 175
Nowres Rafed Avatar answered Sep 23 '22 16:09

Nowres Rafed