XHR Request works only partly in Firefox Extension - javascript

My Request looks as follows:(obviously with a different url, which is different from the visited page)
var url = "https://example.com/example.json"
var request = new XMLHttpRequest()
request.onreadystatechange = function () {
if (this.readyState == 4 || this.status == 200) {
console.log(this.readyState, this.status)
var arr = JSON.parse(this.response)
// Do stuff with the response...
}
};
request.open("GET", url)
request.send()
In Chrome it always works.
In Firefox it works when i execute it in the popup.js of the Addon (included in the extension popup.html, but it doesnt work in the content script, what? :o
From the Console Log im getting Status 0 when its executed from the content script.
Is there any small workaround to make it work? I mean isnt this just very basic stuff...?
I also tried Javascript fetch, but there i have the exact same Problem.... :/

Related

Link triggering XMLHttpRequest

I have made a simple XMLHttpRequest which does work, it sends request etc. Just like in W3 schools.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demox").innerHTML = this.responseText;
}
};
xhttp.open("POST", "textx.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=" + textxx);
}
The problem starts when I try to trigger the request by clicking a link, which sends me to the php file which processes the request. I find it hard to understand on my current level why it doesn't work, since it worked with simple forms and such.
I get:
"Notice: Undefined index: fname ..."
So, I assume, it means the variable wasn't sent. Can someone explain? Or is there way to debug the things that are being sent from one page to another. All I found was a debugger in chrome which indeed captures the requests, but has no real use, since I get sent to the textx.php page and all is lost.
Not really sure, where your problem might be, maybe try:
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "textx.php", true);
xhttp.onreadystatechange = function() {
if (this.readyState === 4){
if(this.status===200 || this.status===0){
document.getElementById("demox").innerHTML = this.responseText;
}
};
var fname = "fname=" + textxx;
xhttp.send(fname);
}
You might console.log(xhttp); and see the step by step profile and find out where the problem might be.
Either way, I am still not sure, but I uploaded my page(code) to a hosting server and the code worked. PHP didn't show any warnings and all went as planned. The problem it seems has to do something with running a local server(WAMP). Changing PHP version didn't help. I may need to dig a little deeper on this.

How to open popup div after sending xml http request?

I am building an extension that should help users use certain site more easily.
Now I am new to AJAX,XML and everything similar so this can be easy question,but I am not sure.
On that website, after clicking on one button, it send xmlhttprequest and after receiving some information it opens a popup div(Displays personas stats etc. and has buttons that are unique for that persona).
Now I wrote the exact same xmlhttprequest that is being sent to server after clicking the button,but after getting the information that is being asked for,it doesn't open anything(which is logical) but I don't know how to open it.
var request = new XMLHttpRequest(),
userz = '76561198364912967',
url = 'https://www.[WEBSITE-NAME].com/api/v1/getuserinfo/?steam_64='+userz,
data = 'steam_64=76561198364912967',
token ='OAuth 3539383833353a313a7b66383738626464332d616536612d343132642d626466342d6136313462366164396139317d';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('GET', url, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('authorization', token);
request.send(data);
Now this is the code and I know that it might not be this language that I am asking for but I think that it is.
I get same response when clicking on button(that site has) and running my script
This is popup div's html code
This is how div looks
Big gradient button has different request data(after clicking it) for each persona that div is opened for.Therefore it has to have something to do with previous request.
The goal is not to make a popup that does nothing, I need to trigger the creation of div that has some functions(like that website makes it)
Cheers!
try using: request.responseText
like this:
var res=request.responseText;//answer from application or server
var elm=document.createElement("div");
elm.innerText=res;
document.body.append(elm);
If you want to make a popup this should work:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let mod=document.createElement("DIV");
document.body.appendChild(mod),mod.className="modal";
let con=document.createElement("DIV");
mod.appendChild(con),con.className="modal-content";
let c=document.createElement("SPAN");
c.className="close",
c.innerHTML="×",
c.setAttribute("onclick","this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)"),
con.appendChild(c);
let p=document.createElement("P");
con.appendChild(p),
p.innerHTML=request.responseText;
}
};
and some CSS:
.modal{display:block;position:fixed;z-index:1;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:#000;background-color:rgba(0,0,0,.4)}.modal-content{background-color:#fefefe;margin:15% auto;padding:20px;border:1px solid #888;width:80%}.close{color:#aaa;float:right;font-size:28px;font-weight:700}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer}
Demo

XMLHttpRequest does not seem to do anything

i have been trying very unsuccessfully to download a binary file from my server using jquery-ajax, which i finally gave up. so now i am trying to use XMLHttpRequest instead. however, i cannot even get a simple example working.
strangely enough, this code does not appear to do anything. i copy/pasted this from w3schools and this example is near identical to many other examples. it does not work for me in either chrome or FF:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Action to be performed when the document is read;
}
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();
we go into the onreadystatechange function only once, on the open() statement with an xhttp.readyState equal to one, but not on the send() step. i should think it would at least throw some kind of error rather than do nothing at all.
also, as an experiment, i purposely fed the open() a bad url - but again no reply.
can anybody tell me what i might be doing wrong?
thank you very much.
Your code looks correct to me, which points to some external cause.
Is your code flowing all the way through to the end of the execution context? Browsers will hold onto network requests until the engine yields back to the browser.
For instance:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Action to be performed when the document is read;
}
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();
while(true){}
will never send the call.

Text file comes back empty when loading with Ajax javascript

I've searched and searched and could not find a solution for this:
I'm trying to load .txt file contents with Ajax but the file comes back empty.
I checked the ready state and status. ready state is 4 which means that connection was set, data received , status is 0 which means error for loading http but I read on a forum that it is ok for a local file.
I really don't know what to do.
all help will be appreciated!
this is my code:
<script>
function load() {
var selectedValue = document.getElementById("mySelect").value;
var xhttp;
alert("in func")
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
try{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && (xhttp.status == 200 || xhttp.status == 0)) {
document.getElementById("textDiv").innerHTML = xhttp.responseText;
alert(xhttp.responseText);
}
};
if(selectedValue == "Year 1"){
xhttp.open("GET", "file://year1.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 2"){
xhttp.open("GET", "year2.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 3"){
xhttp.open("GET", "year3.txt", true);
xhttp.send(null);
}
}
</script>
The issue is most likely the file protocol: file://year1.txt
try using a relative path instead, ie ./year1.txt
Edit..
I missed this the first time around.. you will get several hits to your callback function on a successful call. You'll get one where the status is zero first, then if successful you'll get another one with a 200. Why are you checking for both?
change this...
if (xhttp.readyState == 4 && (xhttp.status==200 || xhttp.status==0))
to this...
if (xhttp.readyState == 4 && xhttp.status==200)
OK! after EXTENSIVE research the problem was the infamous cross origin request problem (which does not allow access to local files as part of a security measure to insure you don't upload infected files &ct)
the solution is :
when initializing the variable for the XMLHttpRequest write:
xhttp = new XMLHttpRequest({mozSystem: true});
(notice the {mozSystem: true} inside the request)
AND IT SOLVES THE PROBLEM!!!
Thank you for your time, I hope this helps someone :)
My previous answer worked but not for long - after I restarted my computer the ajax stopped working at started throwing the cross origin error again. so- the best option I found that also works for all the browsers I checked (chrome, IE), is to set up a local server and run it from there.
here is a link for instructions:
https://www.maketecheasier.com/setup-local-web-server-all-platforms/
Good luck!

Is there a way of determining whether a blob URL points to something?

Currently working on a project where we get a bunch of image over AJAX.
We do quite a lot of these, and it seems that IE11 seems to lose quite a few of them.
We get the image, call "URL.createObjectURL", get a valid URL, but by the next line, the image is gone. This works fine in other browsers, I'm assuming we're hitting some limit in IE.
Is there a nicer way of detecting if this URL is valid than trying to load it up?
Seems a little redundant to have to:
AJAX a file.
Get its address on the user's comp.
AJAX that address to make sure it's there.
Code:
var urlObj = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
active--;
if (this.status == 200) {
var blobUrl = urlObj.createObjectURL(new Blob([this.response], {type : 'image/jpeg'}));
image.setSource(blobUrl);
}
}
}
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.send();
So if you call this A LOT (with different URLs) - the blobUrl that we pass to setSource is a sensible looking object URL, but when you try and use it, you get an error.
IE has either cleared up the memory, or lost the image or something. Bearing in mind we're not changing the page, losing the session, or revoking the blobUrl.
The only way I can think of to check if this has happened (i.e. that blobURL no longer points at anything), is to fire another AJAX request at the blobURL, and check it returns 200 etc....
Is there a better way? I'm imagining not.
I've "carved" this code-chunk from a larger block, so if there are any obvious mistakes there that's why. It works around 95% of the time. If I fire the AJAX "check" afterwards, and load the image again on a fail that fixes the issue.
Weird IE behaviour. Anyone else seen this?
More info: We're not using pdf.js, but same problem is reported here: https://connect.microsoft.com/IE/feedback/details/813485/resource-blob-not-found-when-using-url-createobjecturl-blob
This is (more or less) the check that we are using:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4){
if (this.status == 200 || (this.response && this.response.type && this.response.type == "image/jpeg")) {
success(blobUrl);
}
else {
fail(blobUrl);
}
}
}
xhr.open('GET', blobUrl);
xhr.responseType = 'blob';
xhr.send();
Have to use that weird response.type check, because Firefox returns with status == 0.

Categories

Resources