XMLHttpRequest not defined

Hi,

I am fairly new to programming but I decided to tackle on developing a small Firefox extension. When I am trying to use XMLHttpRequest method, it keeps throwing the error message as attached (both cfx and jpm). I found the code below online so I have used it but no luck.

function reqListener () {
    console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();

I also have tried: “(cmd prompt) npm install xhr2”,
then adding the line:

var XMLHttpRequest = require('xhr2');

and still no luck.

Any help would be much appreciated. I am using Firefox 39.0. I also have Developer’s Edition installed, version 41.0a2.

Thank you,

Hi.
If your using the code inside a page-mode (I mean a script running on a web-page, see https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/page-mod) It should definitely work, because that’s the JavaScript way to do it. But from what I can see you’re trying to make a request from the main.js module.
You’re suppose to use https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/request for making requests inside a common.js modules that runs the logic of the add-on because you don’t have access to all the JavaScript API like in a normal webpage.

Or the same thing worded slightly differently: https://stackoverflow.com/a/8804481/785541

Yes, I am intentionally pitching Stack Overflow here - most of the basic questions are already answered there.

Hi,

I did come across the mentioned post on StackOverflow.com but I guess I didn’t comprehend your answer fully due to lack of knowledge. Sorry Wladimir. Now, having a vague understanding of 1) Request; 2) xhr and xhr2, and its restricted usage in Firefox SDK, and 3) not (yet) wanting to explore outside of the small zone of index.js (or main.js in cfx), I think “Request” seems to be capable of achieving what I ultimately want.

I have further question though:
What is the difference between response.text and response.json? I wanted to explore response.json, as this seemed to have more flexibility and would be easier to fetch data than plain text, as it is already organized in an object, from what I have read and understood. But, unlike .text, I keep getting “null” with .json.

So websites give back json text, and you can JSON.parse that right away with xmlhttpequest