XMLHttpRequest always returns undefined in IE9

I would like to know why this code works on firefox, chrome and IE10, but not in IE9

var ajaxReq = new XMLHttpRequest(); var params = "name="+$('#name').val() var url = "register.php"; ajaxReq.open("POST", url, true); ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxReq.setRequestHeader("Content-length",params.length); ajaxReq.setRequestHeader("Connection", "close"); ajaxReq.onreadystatechange = function(){ if(ajaxReq.readyState == 4 && ajaxReq.status == 200) {alert(ajaxReq.response)} //<---this results undefined } 

The code contained in the php file itself does not matter, because for some evidence I shoot it very minimally:

 header('Content-Type: text/json'); echo 'response'; exit; 
+4
source share
1 answer

Instead of .response it should be .responseText or .responseXML - see HTTP response . In your case, I assume the change to alert(ajaxReq.responseText); will be fixed.

response not a property of the XMLHttpRequest object, so the JavaScript engine throws an undefined error.

From the above documentation:

responseText will contain the server response in plain text using the appropriate user agent

therefore, use responseText for all text in a regular format except XML , which includes JSON , as it is a plain text format.

+5
source

Source: https://habr.com/ru/post/1484154/


All Articles