Star089 Star089 - 3 months ago 21
Ajax Question

How to get a data from html element from ajax responseText without jquery

I'd like to get data from ajax response, but this code not working:

var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {

if (request.readyState == 4) {
alert(request.responseText.document.getElementById('div1').innerHTML);
}


}


console give me this information :Uncaught TypeError: Cannot read property 'getElementById' of undefined.

any ideas ?:)
Regards

Answer

You can use DOMParser to convert html string to document fragment

var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(request.responseText, "text/html");
    var elem = doc.getElementById("div1");
    alert(elem.innerHTML);
  }
}

alternatively, you can set the responseType to document

var request = new XMLHttpRequest();
request.open("GET", "file.html", true);
request.responseType = "document";
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var doc = request.response;
    var elem = doc.getElementById("div1");
    alert(elem.innerHTML);
  }
}

plnkr http://plnkr.co/edit/lkpveDD31fYY1gmflK9W?p=preview