XHR status 0, readystate 1 on localhost - javascript

Working on my own project. I'm sending an XMLHttpRequest to localhost from Firefox 44 to XAMPP. I'm receiving a status of 0 and a readystate of 1. Here's the code in question.
function sendReq(php,segment){
alert("sendreq called ");
//we out here getting 0 statuses. check out cwd, check out what php value is,
xhr.open("POST", php, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = getData(segment);
xhr.send();
}
//callback function for ajax request.
function getData(div){
if ((xhr.readyState == 4) && (xhr.status == 200))
{
var serverResponse = xhr.responseText;
div.innerHTML = serverResponse;
}else{
div.innerHTML = "<p>loading!</p> ready state: " + xhr.readyState +"</br> status: "+ xhr.status;
}
}
I've read elsewhere the RS:1 / S:0 XHR properties indicate a unsuccessful cross domain request, but this is all occuring on localhost, with the files all in the same directory, and when inspecting the XHR response in Firebug, the return text is in there.
I've built a login to this page almost identical code and it works, its only pointing to a different .php file. Comparing the two and googling around are not enlightening me. So any advice is welcome. Thanks!

You're executing the getData() function once, on pageload, and returning undefined to the onreadystatechange handler, as that's what happens when you add the parentheses.
It has to be either
xhr.onreadystatechange = getData;
Note the lack of parentheses, or if you have to pass arguments
onreadystatechange = function() {
getData(segment);
}

Related

If HEAD-HTTP-Requests only fetch the HTTP-Header, why my XHR-request has a reponseText?

Today I researched about HTTP-methods and the differences between GET and HEAD in detail.
In theory I know, that HEAD only returns the HTTP header, not the HTTP body. Its useful to get information about ressources without downloading them completly.
I made a little Script using XHR to check out a HEAD-reques and tested it in Firefox 50.0.2.
http://codepen.io/anon/pen/oYqGMQ
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function () {
if (req.readyState === 4 && req.status === 200) {
alert("got response \n" + req.responseText);
}
}, false);
req.open("HEAD", location.href, true); // this is a HEAD-request, why I get a responseText?
req.send();
Why the HEAD-Request receives the complete data in the reponseText-property? I thought HEAD-Request will not receive any data of the body.
I can't see any difference between HEAD and GET.
Am I missing a point? I am using Firefox.

Empty response of XMLHttpRequest

In my Java Web application I am calling ajax request as below.
<script type="text/javascript">
function selectTableHandler() {
console.log("indise selectTableHandler");
var xhttp = new XMLHttpRequest();
var selectedTable = document.getElementById('selectTable').value;
alert(selectedTable);
xhttp.open("GET", "populateTableColumList.action?tablename="
+ selectedTable, true);
xhttp.send();
console.log(xhttp.responseText);
}
</script>
The Action is calling and returns status code 200 as below.
Remote Address:[::1]:8080
Request URL:http://localhost:8080/ReportBuilder/populateTableColumList.action?tablename=films
Request Method:GET
Status Code:200 OK
But, it gives empty response of XMLHttpRequest. The line console.log(xhttp.responseText); prints nothing. Also, there is no error in console log.
Any suggestions would be appreciated.
Thanks
You need to add a callback function to get the result of the ajax request.
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
Your ajax request is asynchronous. That means it returns the result some time LATER. You will need to install an event handler for onload or onreadystatechange to get the result.
There are plenty of Ajax tutorials on how to do this. Here are a couple useful references:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
If you want to use vanilla js you have to attach event handler onreadystatechange which will handle response, but my advice instead of use vanilla js, use library like jQuery to initiate the ajax request. It will be more easily and it will run without problems on all types of browsers. see here. If you want vanilla js, here is a sample snippet:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE ) {
if(xhttp.status == 200){
console.log(xhttp.responseText);
}
}
}

First XHR request very slow in QML(javascript running on v8)

I have a QML page (Qt Quick 2) that makes an XHR request to an external server. Right now the server is running on my local machine and the first time this request is made it takes ~1.5 seconds. Each subsequent request is under 100ms.
When I make this same request using a browser I get a response in under 10ms everytime, so I know the problem isn't there.
Here is the offending code. Any ideas?
function login(key) {
var xhr = new XMLHttpRequest();
var params = "Fob_num=" + key;
xhr.open("POST","http://localhost:9000/customer_login",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if ( xhr.readyState == xhr.DONE) {
if ( xhr.status == 200) {
handleResponse(xhr.responseText);
} else {
console.log("error with login--status: " + xhr.status)
displayErr("Oops, something's wrong. Please try again.")
}
}
}
xhr.send(params);
}
The problem isn't with handleResponse() function, I've already tried replacing it with a console.log(“response”), and it still takes just as long. I also tried replacing localhost with my ip.
You may want to create a dummy XMLHttpRequest instance in a dummy QML component that you asynchronously load with a Loader. Just an idea. Perhaps creating the first XMLHttpRequest instance takes long?

How can I tell XHR is sent to server using readyState?

This question is related to my prior question:
Is READYSTATE_LOADED across browsers?
So I know that readyState is not reliable across browsers. I'm currently just trying to do a proof-of-concept in ANY browser at this point.
I'm in my plugin and have code like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
self._onComplete(id, xhr);
}
else if (xhr.readyState == 2 ){
self._onSent( id, xhr );
}
};
If I log the callbacks, "sent" fires immediately before "complete", AFTER my server side script responds. Am I misunderstanding what readyState 2 is? I tried 1 for kicks and that didn't fire before the server responded either.
I took a look into the upload object of the xhr object, which does at least have a "progress" event, but I still didn't see anything about progress being done. In fact if the last progress was at 97%, it will not fire at 100% as the file completes sending to server. Therefore while the server processes the upload, the progress hangs at 97% before the readyState becomes 4.
This makes the user think the upload stalled even thought it actually went up all the way.
There is no state to check to see when a request has been sent off.
readyState 2 means that the server has responded and all headers have come in. This is fired right before the main body section of the request comes in.
Your best bet is to fire your own event when you issue the send() command.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
self._onComplete(id, xhr);
}
else if (xhr.readyState == 2 ){
// Headers received
}
};
xhr.send(data)
self._onSend( id, xhr );
4.6 States
UNSENT (numeric value 0) The object has been constructed.
OPENED (numeric value 1) The open() method has been successfully
invoked. During this state request headers can be set using
setRequestHeader() and the request can be made using the send()
method.
HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been
followed and all HTTP headers of the final response have been
received. Several response members of the object are now available.
LOADING (numeric value 3) The response entity body is being received.
DONE (numeric value 4) The data transfer has been completed or
something went wrong during the transfer (e.g. infinite redirects).
http://www.w3.org/TR/XMLHttpRequest/#states
EDIT
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
self._onComplete(id, xhr);
}
else if (xhr.readyState == 2 ){
// Headers received
}
else if (xhr.readyState == 1 ){
// xhr.open() called
// You can set headers here amoung other things
xhr.send(data)
self._onSend( id, xhr );
}
};
xhr.open(method, url, async, user, password)
http://www.w3.org/TR/XMLHttpRequest/#the-open-method

XMLHttpRequest receiving no data or just "undefined"

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.

Categories

Resources