Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Response Header location from jQuery Get?

So I am trying to get the location from a header response via jQuery get. I tried using getResponseHeader('Location') and getAllResponseHeaders() but they both seem to return null.

Here's my current code

$(document).ready(function(){
   var geturl;
   geturl = $.ajax({
      type: "GET",
      url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
   });
   var locationResponse = geturl.getResponseHeader('Location');
   console.log(locationResponse);
});
like image 958
raeq Avatar asked Jun 27 '12 10:06

raeq


People also ask

Can Javascript read response header?

While you can't ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it.

What is get method in jQuery?

jQuery get() method. The get() method is an inbuilt function in jQuery. It loads data from the server using the HTTP GET request. It is used for making a simple GET request. It returns XMLHttpRequest object.


2 Answers

The headers will be available when the asynchronous request returns, so you will need to read them in the success callback:

$.ajax({
    type: "GET",
    url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
    success: function(data, status, xhr) {
        console.log(xhr.getResponseHeader('Location'));
    }
});
like image 190
Bergi Avatar answered Oct 21 '22 13:10

Bergi


for some headers in jQuery Ajax you need to access XMLHttpRequest object

var xhr;
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
  xhr = _orgAjax();
  return xhr;
};

$.ajax({
    type: "GET",
    url: 'http://example.com/redirect',
    success: function(data) {
        console.log(xhr.responseURL);
    }
});

or using plain javascript

var xhr = new XMLHttpRequest();
xhr.open('GET', "http://example.com/redirect", true);

xhr.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    console.log(xhr.responseURL);
  }
};

xhr.send();
like image 41
uingtea Avatar answered Oct 21 '22 14:10

uingtea