XMLHttpRequest receiving no data or just "undefined" - javascript

i try to make a Firefox Addon which runs a XMLHttp Request in Javascript. I want to get the data from this request and send it to *.body.innerhtml.
That's my code so far...
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
setTimeout(function() { set_body(xhr.responseHtml); }, 6000);
Instead of receiving the data, I get "undefined". If I change xhr.responseHtml to responseText I get nothing. I don't know why I'm getting nothing. I'm working on Ubuntu 12.04 LTS with Firefox 12.0.
If you need any more details on the script please ask!
Update:
set_body Function
document.body.innerHTML = '';
document.body.innerHTML = body;
document.close();

Update SOLVED:
I had to determine the RequestHeaders (right after xhr.open):
xhr.setRequestHeader("Host", "xxx");
For following Items: Host, Origin and Referer. So it seems there was really a problem with the same origin policy.
But now it works! Thanks to all!

when you set the last param of open to true you are asking for an async event. So you need to add a callback to xhr like so:
xhr.onReadyStateChange = function(){
// define what you want to happen when server returns
}
that is invoked when the server responds. To test this without async set the third param to false. Then send() will block and wait there until the response comes back. Setting an arbitrary timeout of 6 seconds is not the right way to handle this.

This code should work:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
set_body(xhr.responseText);
}
};
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
Make sure that you are getting a correct response from URL http://xx.xxxxx.com. You may have a problem with cross-domain calls. If you have a page at domain http://first.com and you try to do XMLHttpRequest from domain http://second.com, Firefox will fail silently (there will be no error message, no response, nothing). This is a security measure to prevent XSS (Cross-site scripting).
Anyway, if you do XMLHttpRequest from a chrome:// protocol, it is considered secure and it will work. So make sure you use this code and make the requests from your addon, not from your localhost or something like that.

Related

Ajax Call empty response on Google chrome Mobile

i searched for an answer that fix my problem a lot, but none of the topic fit my scenario..
I have to make an AJAX call inside my application, it work fine on ALL desktop browser, and on SOME mobile browser (for example on my ASUS zenPhone native browser it work correctly, even on my iPhone from work (FF and Safari)) but no way in google Chrome (mobile), in this one the call complete but the response it's empty (only empty, no error provided)... i ask some friend to test it too and similar result occours (empty response) .... i have an https server and an https endpoint
there is my code:
<script>
var x = Math.floor((Math.random() * 10000000) + 2000);
var data = JSON.stringify({
"Token": x,
"Subject": "testAPI"
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
var dataJ = JSON.parse(this.responseText);
var dataA = dataJ.Questions;
alert(dataA[0].img);//this is already empty on my mobile :(
dataA.forEach(function(entry) {
//console.log(entry);
});
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
</script>
Server side CORS are enabled, and as i said it works flawless on all desktop i tested on ... i don't know if i can provide the url to you guys(i have to ask # the API provider) but if you give me some hints it would be nice ...
thanks a lot for your time!
[EDIT]
after some trouble i get an error(Testing remotly from my phone to my PC with dev tools)
Failed to load resource: net::ERR_INSECURE_RESPONSE
on the other device i didn't get this error...
This is a long shot but, try to set the content type header to :
xhr.setRequestHeader("content-type", "text/plain");
This should suppress the CORS preflighting done by chrome which causing the empty response.

XMLHttpRequest, send and security restrictions

I thought I could catch an error in send like this
try {
xhr.send();
} catch(e) {
// fix-me: With the
// bookmarklet on a https page
// you can't even send a HEAD
// request due to security
// restrictions. Check for
// this case here.
console.log("xhr.send, e=", e, method, window.location.href, url)
debugger;
}
console.log("I am here now");
However I never get to that console.log statement in the catch block after xhr.send.
In the console I instead get a message like this.
Mixed Content: The page at 'about:blank' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://m.org/'.
This request has been blocked; the content must be served over HTTPS.
I am here now.
Is it supposed to work this way? (I am using Google Chrome.)
Is there any way to find out that there was an error? (Except looking in the console. ;-) )
UPDATE
#giuscri added the very good question if I did consider that this is async. I actually missed that it could be, but it is not. A bit surprisingly. ;-)
Please see the this example. It contains this code:
var url = "http://nowhere.org/";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log("onreadystatechance, readyState=", xhr.readyState);
};
xhr.onprogress = function(event) {
console.log("onprogress, readyState=", xhr.readyState);
console.log("onprogress, event=", event);
};
xhr.onerror = function(event) {
console.log("onerror, readyState=", xhr.readyState);
console.log("onerror, event=", event);
};
var method = "HEAD";
xhr.open(method, url, true);
try {
xhr.send();
} catch(e) {
console.log("xhr.send, e=", e, method, window.location.href, url);
}
console.log("After send");
When you run this page from https:// (as in the link above) the onerror function is not run. If you run the same example from file:// then onerror is run.
Connecting from HTTPS to HTTP URIs drops the security given by the underlying encryption. Web browsers blocks such requests until explicitly allowed by the user in order to prevent data leakage over plaintext connections. Further, there is also a change in origin (scheme, domain, port).
I allowed Mixed Content for the page you linked and I got the error about the different origin in console. Looks like the code works.
By the way, support for synchronous requests using XMLHttpRequest is deprecated, because it blocks user interaction until the request completes.

XMLHttpRequest receiving undefined

I'm making a widget on iphone but I can't get data from the url.
On IE, I can get data. However, on chrome and on iphone I can't get the data but it only shows undefined instead of data.
function a() {
var url="www.xxx.xxx";
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
xmlDoc = request.responseXML;
}
please help me!! I'm really appreciated for any answers.
Create a function something like below,to receive the data from server.
request.onreadystatechange = function(){
if(request.readyState == 4){
console.log(request.responseText);
}
}
Please make sure that you are making request from the same Origin. That means if you are in site www.abc.com then you can make request for www.abc.com/download/ or www.abc.com/site and so on. But if you request for www.gdb.com then it will probably fail with this error in your console "No 'Access-Control-Allow-Origin' header is present on the requested resource." The browser prevents this activity for security reasons. It needs to be on the same domain.
Try using JQuery sometimes. It's API is very easy to use and is very helpful for doing tasks. You will need to add the script to the page first like this:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You can download the script or use the live version and link to it like above.
Next you can make a call like this to make a GET request. Observer that it returns data when successful. This makes your job easy but remember you need to make call from same domain.
$.ajax({
type: "GET",
url: "http://wwww.something.com"
})
.done(function( data ) {
alert(data);
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
To know more about Cross Site HTTP Requests: CORS
Here is a thread that may help you to understand better: “No 'Access-Control-Allow-Origin'
would setting the responseType work?
call the request.responseType = 'document'; before send.

XMLHttpRequest() JSON throws a network error but similar jQuery .getJSON code works

I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):
jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
function(data){
document.querySelector("output").textContent = data.postal_codes[0].city;
});
However, the website owner don't want jQuery if it's not crucial, so I recoded .getJSON to the request = new XMLHttpRequest(); model:
request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
var data = JSON.parse(request.responseText);
document.querySelector("output").textContent = data.postal_codes[0].city;
};
request.onerror = function() { /* this gets called every time */ };
I've modified my code many times, read documentations over and over again, yet the .onerror function is the only one always displaying. This is the console:
Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".
There could be several reasons as to why this occurs:
1: There's something wrong with the new code
2: There's something in the .getJSON jQuery function (a hack?) that prevents the error from happening
3: There's something crucial in the new code that I have forgot adding
4: There's something with my browser (IE 11 at the moment)
5: Something else?
It would be lovely with some help on this.
DEMO: http://jsbin.com/muxigulegi/1/
That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.
Since you have callback=? in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.
You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.
Create a JSONP request instead.
From http://api.jquery.com/jquery.getjson/:
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
You do have a callback. Which means that the JQuery function can request data from another domain, unlike your XHR call.

Getting Access Denied Error

Getting Access Denied Error on https in IE. while executing ajax call (to my server1) response which has another ajax call While my Ajax call url is on http .By implementing cors I able to execute on http.Tried JSONP also but then it execute my response till it find another ajax call .How to solve ?
below is on myserver1
alert('aaa');
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', 'http://myserver2.com', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr2.send();
xhr2.onload = function () {
alert('fff');
var appCreds = xhr2.responseText;
alert(appCreds);
};
alert('xxx');
In addition to the trusted site requirement I found that the problem was not fixed until I used the same protocol for the request as my origin, e.g. my test site was hosted on a https but failed with any destination using http (without the s).
This only applies to IE, Chrome just politely logs a warning in the debug console and doesn't fail.

Categories

Resources