XMLHttpRequest read progressive data not working? - javascript

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.

Related

How to everytime reload web, and get the newest data from back-end

What my purpose is below
Visting a web and the js.file in this web will load php file, and it will return data to html.
It's meaning every time when I reload web, I will get newest data.
I have try this in js.file
let XML = new XMLHttpRequest();
XML.open('post', url, true);
XML.send('mydata');
then use responseText to get data I want
Indeed, I don't need send any data.
I can do what I want to do, but I am not sure this way is right or not.
Because I think ajax should not use in this case, it must be send something and return something.
What you are saying is you only want to get data without sending anything which is called a http get request, you can do that as below.
function get(url)
{
var xm = new XMLHttpRequest();
// false for synchronous
xm.open("GET",url,false);
xm.send(null);
return xm.responseText;
}
console.log(get('your Url'));
You need to specify the url of your Http Endpoint ( Back-End ).
If your are making a asynchronous request then below code works,,
function get(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
// true for asynchronous
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
get('your url',(responseText)=>{
console.log(responsetext);
});

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

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

Categories

Resources