3

Why is responseType empty?

JavaScript

var xhr = new XMLHttpRequest();
xhr.open(method,url,true);
xhr.onreadystatechange = function()
{
 if (xhr.readyState=='4')
 {
  if (xhr.status==200)
  {
   console.log(xhr.responseType);//[empty]
  }
 }
}

PHP

header('Content-Type: application/json');
//[Validated JSON Data]

No frameworks.

John
  • 1
  • 13
  • 98
  • 177
  • 1
    Empty means empty string? – Felix Kling May 07 '16 at 16:47
  • a console.log of xhr shows the presence of responseType ? – Pietro May 07 '16 at 16:48
  • Browser support is.... unknown: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType#Browser_compatibility – Felix Kling May 07 '16 at 16:49
  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType It can be wmpty string – Pietro May 07 '16 at 16:49
  • Been through all that. Empty string: `console.log(xhr.responseType);`. – John May 07 '16 at 16:49
  • I would avoid to use it, as @FelixKling states, unknown browser compatibility, it is creepy :) – Pietro May 07 '16 at 16:51
  • 1
    Reading the spec it seems like *you* have to assign to this property before you send the request. Not sure if that information is sent to the server or if simply makes the client perform conversions on the response. – Felix Kling May 07 '16 at 16:54
  • That's the kind of anti-intuitive nonsense I expect from CSS. Guess I'll have to use `getResponseHeader`. I'll determine the answer and post it so it'll save someone else the hassle and time of trying to figure out why yet another thing doesn't make logical sense. Thanks guys. – John May 07 '16 at 16:58

1 Answers1

5

As clarified in the comments the new XMLHttpRequest().responseType is intended as a request header and does not represent the media type/mime response from the server (which would have made logical sense). So to test for response types use something along the following lines:

Full Media Type/Mime

console.log(xhr.getResponseHeader('content-type'));//application/json

Specific Media Type/Mime

console.log(xhr.getResponseHeader('content-type').split('/')[1]);//json
John
  • 1
  • 13
  • 98
  • 177
  • 1
    Avoid splitting the header in case the server does not provide it, or provides a malformed type. Instead use `includes`, such as `xhr.getResponseHeader("content-type").includes("json")`. Additionally the server may return the encoding, thus splitting it will possibly result in `json; charset=utf-8` – NotoriousPyro Feb 28 '23 at 16:04
  • @NotoriousPyro Valid, I do object detection though I kept it simple here. – John Mar 16 '23 at 11:02