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.
ajax appears to always follow redirects.
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.
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 .
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With