0

I'm sorry for my bad code, I'm not used to manipulate VanillaJS prototypes object.

I want to getback my XMLHttpRequest response to store it in my CalibObject. But when I got out from my .onload() function after checking readyState and storing it in my Object, I can't get back my XML data.

var CalibObject = function() {
  // this.m_init_loader = new XMLHttpRequest();
  
  var xhr = new XMLHttpRequest();
  xhr.open("GET", xmlIniUrl);
  xhr.responseType = 'document';
  xhr.overrideMimeType('text/xml');
  xhr.send();
  
  xhr.onload = function() {
    if (xhr.readyState === 4) {
      CalibObject.xml_data = xhr.response;

      console.log("CalibObject.xml_data when calling .onload() inside CalibObject(); : ");
      console.log(CalibObject.xml_data);
      console.log("---------------------------------------------");
    }
  };

  this.m_init_loader = CalibObject.xml_data;
  console.log("this.m_init_loader before the close of CalibObject(); : ");
  console.log(this.m_init_loader);
  console.log("---------------------------------------------");
};

CalibObject.prototype = Object.create(Object.prototype);

CalibObject();

console.log("CalibObject.prototype.m_init_loader after call of CalibObject(); : ");
console.log(CalibObject.prototype.m_init_loader);
console.log("---------------------------------------------");

And here are my console logs :

this.m_init_loader before the close of CalibObject(); : 
null
---------------------------------------------
CalibObject.prototype.m_init_loader after call of CalibObject(); :  
undefined
---------------------------------------------

CalibObject.xml_data when calling .onload() inside CalibObject(); : 
#document
---------------------------------------------

The last log is my correct XML data printed.

Could you indicate me what's wrong please ? And How to access my XML Data from other JS files please ?

Balianos
  • 13
  • 4
  • 1
    The data is only available after it's loaded. Your first two console logs get called before the `onload` is triggered, so the data is `null`. If you want to execute some code after the data is loaded, you have to place that code in the `onload` function as well. What are you trying to achieve what that `prototype` call? – Kokodoko Nov 27 '20 at 14:26
  • Thanks for your return. In fact I need to use that data outside my function, by storing it in my CalibObject.prototype.m_init_loader and being able to access the data in another method. In my case I need to access the XML data in that function : ``` CalibObject.prototype.onInitLoaded = function(event) { CalibObject.xml_data = this.m_data_loader.data; for (var item = 0; item < CalibObject.xml_data.item.length; item++) { ... more code with binding data for fields values ... ``` – Balianos Nov 27 '20 at 15:25

0 Answers0