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

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

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.

XHR status 0, readystate 1 on localhost

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);
}

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?

response cookies and 2 asynchronous xmlhttp request using chrome.cookies extension

I have 2 different XMLHttpRequest objects making asynchronous requests to the same web service. The web service sends back a cookie in the HTTP response headers, that I can read with the chrome.cookies.read extension (the request is cross-domain).
Each xhr reads the same cookie by name, but the value of the cookie after each response will be different, as it is a unique token for each requester.
So I want to store each cookie value per request, just after receiving the HTTP response, for later use.
So here's what my code is currently doing:
var my_cookie_value = [] ;
function begin()
{
for (var i = 0 ; i < 2 ; i ++)
{
sendRequest(some_url, i);
}
}
function sendRequest(some_url, thread)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
readCookie(thread) ;
}
}
xmlhttp.open("GET", some_url, true);
xmlhttp.send();
}
function readCookie(thread)
{
chrome.cookies.get(
{
"url" : some_domain,
"name" : "mycookie"
},
function(cookie)
{
if (cookie != null)
{
my_cookie_value[thread] = cookie.value ;
}
}
);
}
However because chrome.cookies.read uses a callback function with no guaranteed time to fire, I am finding the cookie values get mixed up (or repeated) for each thread, even though they were returned from the server as distinct values.
I think what can happen is:
thread 0 sends request
thread 1 sends request
thread 0 receives response
thread 0 requests cookie value callback
Arrgghh!!...worst case scenario coming up...
thread 1 receives response
thread 1 requests cookie value callback
thread 0 cookie callback fires and cookie value (FOR THREAD 1) is copied into my_cookie_value[0]
thread 1 cookie callback fires and cookie value (FOR THREAD 1) is copied into my_cookie_value[1]
This is obviously not what I wanted. my_cookie_value[0] and [1] both contain the token for thread 1.
So finally to the question: Is there another solution for this? I cannot rewrite the server code, I can only access the client.
I am wondering why oh why is reading a cookie done by a callback function??
Set up var that tracks if you currently have a request active. Something like var currentRequest = false and set it to true before starting a request and set it to false after a request is complete. Before starting a request check if there is an active request and if there is either delay or create a queue of pending requests.

XMLHttpRequest read progressive data not working?

I'm having issues with XMLHttpRequest downloading progressive data. I get a state 2 and than state 3. After state 3 it never gets called again. What am I doing wrong? I read somewhere I need to flush the data but how do I do that?
Here is my code:
var xmlHttp = new XMLHttpRequest();
// try to connect to the server
try
{
// initiate server request
xmlHttp.open("GET", "http://208.43.121.133:8164/;", true);
xmlHttp.setRequestHeader("Icy-Metadata", "1");
xmlHttp.onreadystatechange = function()
{
alert("status: "+xmlHttp.status);
alert("State: "+xmlHttp.readyState);
if (xmlHttp.readyState == 3)
{
alert(xmlHttp.responseText);
}
};
xmlHttp.send(null);
}
// display an error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
}
am I allowed to read the xmlHttp.responseText when readyState is 3?
The problem is most likely with this segment:
if(xmlHttp.readyState == 3) {
alert(xmlHttp.responseText);
}
The reason being is that the xmlRequest isn't complete yet (readyState=4 when complete). When you requested the responseText prematurely, it triggered an error and stopped the code from finishing.
So you would change it to:
if(xmlHttp.readyState == 4) {
alert(xmlHttp.responseText);
}
Kranu is correct, you're not allowed to read responseText when readyState is 3. See http://www.davidflanagan.com/2005/08/xmlhttprequestreadystate-3.html
The solution is to send a message at a time. When you receive one message, just make another XHR. That's how google does (did?) server push.

Categories

Resources