Empty response of XMLHttpRequest - javascript

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

Related

Exchange API using javascript

I'm using javascript to use the API on this site https://www.luno.com/en/api and I don't understand why I am not receiving any data. When if I just enter this url: https://api.mybitx.com/api/1/ticker?pair=XBTZAR I do receive data in the broswer.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("luno").innerHTML = myObj.bid;
}
};
xmlhttp.open("GET", "https://api.mybitx.com/api/1/ticker?pair=XBTZAR", true);
xmlhttp.send();
Why is it not returning anything?
You have a trouble with CORS requests.
You can see similar error on your developer console:
You can't call API from JS code because api.mybitx.com blocks cross domain request.
You have a several solutions:
Create own server side API method.
Call this method from your JS code.
Inside the API method call api.mybitx.com API using WebRequest or RestSharp.
If you want to do it only on JS code, then you need to use EasyXDM library.
For me the first solution is more simpler and more correct.

Why we handle the response before the request in AJAX?

I am new to AJAX, As i understood that the handler function executes when response is ready.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
And then we create and send our request
xhttp.open("GET", url, true);
xhttp.send();
does it make sense to handle the response while not sending the request yet !? Thanks
It makes sense because we may get the response while the response event handler was not set. Also, we do not handle the response right away, but we define the handler function which deals with the response.
On the other hand, in 99% of cases one will make no mistake to define the handler after the send(), in case he does not care whether the request failed immediately.
So, if there is no other way, than define the response handler after sending the request, but in all other cases do it a proper and secure way - before.

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

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