onreadystatechange is never getting called - javascript

I have created XHR and I am also getting response from server correctly.
But for some reason the callback is not happening. Please help.
function uploadDr(){
var url = "UploadExcelServlet";
if (req != null) {
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.onreadystatechange = callBk;
req.setRequestHeader("Content-Type", "multipart/form-data");
req.send();
} else {
alert("Null Request");
}
}
function callBk(){
if (req.readyState == 4){
if (req.status == 200){
alert(req.responseXml);
} else {
alert(req.statusText);
}
}
}

For GET requests you don't need set the "Content-Type" header, because the data are always passed in the URL.
And maybe you need set request data to send as follows:
req.send(null);
Then test readyState in callback function:
function callBk(){
console.log(req.readyState); // don't stop the script by using alert!
// other stuff
}
Make shure that readyState is not equal to 0 (XMLHttpRequest.UNSENT).

Related

XMLHTTPRequest onreadystatechange readyState is always 1?

My readyState in my onreadystatechange callback seems to be stuck at 1.
let req
function reloadData(){
let now = new Date()
url = 'liveData?' + now.getTime()
try {
req = new XMLHttpRequest()
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP")
} catch (oc) {
alert("No AJAX Support")
return
}
}
}
req.onreadystatechange = processData
req.open("GET", url, true)
req.send(null)
}
function processData(){
alert(req.readyState)
// If req shows "complete"
if (req.readyState == 4){
dataDiv = document.getElementById('currentData')
// If "OK"
if (req.status == 200)
{
// Set current data text
dataDiv.innerHTML = req.responseText
}
else
{
// Flag error
dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>'
}
}
}
the request itself works and I log when /liveData gets a request and I get that log as well. I have no errors and the alert itself works so it is calling properly, but the readyState is at 1 at all times.
Turns out the server just wasn't sending a response, thank you Heretic Monkey for pointing that out in the comments.

Detect JSON exist

I have question about chechking file exists.
I have this piece of code.
function fileExists(url) {
if (url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
console.log("exists");
return true;
} else {
console.log("no exists");
return false;
}
}
But it says me that file is exists. But it doesn't exists. In fact on my URL is 404 error XML file. Is possible somehow detect if requested URL is JSON? I need to return true only if checked file is JSON.
Thank you
Since this is a synchronous request, you can just try to parse the responseText you get back and if it fails to parse, you know it's not JSON:
var res = req.responseText;
try {
res = JSON.parse(res);
console.log('json', res);
} catch (e) {
console.log('not json')
}
If it were not a synchronous request, this would work:
If you look at the XMLHttpRequest docs, you'll see that in order to receive data back from an XMLHttpRequest, you need to add a callback function:
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
// Request finished. Do processing here.
}
}
If you wanted to check if your request is JSON, you could do this:
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
var res = this.responseText;
try {
JSON.parse(res);
console.log('json', res);
} catch (e) {
console.log('not json')
}
}
}

xmlHttpRequest status = 0

I have a website (wagtail CMS) running at AWS at domain:8000 and my API running at domain:8801
On my webpage I try to get some info from API by using JS (Access-Control-Allow-Origin header is set correctly at API, it's a django-based app)
Unfortunately the following code returns only xhr.status = 0 and empty responseText no matter what I try to access.
When I put domain:8000 at xhr.open('GET','http://domain:8000',true) everything works just fine, I see my html code.
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
On the API side I see all my requests, status=200 in server console.
You're supposed to use a callback function to catch the response from a request using the XMLHttpRequest object. Do something like this instead:
xhr.addEventListener('readystatechange', function() {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
} else {
alert( "SUCCESS" );
}
}
});
Look here for docs and an examples on doing that.
You need to wait for xhr.readyState == 4 before xhr.status is at all valid (actually I think it's valid at 3, but lets keep consistent with 99.999% of code in the wild)
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
};
xhr.send();
}

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

How to wait for ajax request to complete in javascript when synchronous option is not available?

I'm trying to wait for the AJAX request to complete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ');
that.debug('-- ResponseText: "'+data+'"')
}
}
}
while (ajaxFinished == false) {
}
this.debug("-- open connection");
xmlhttp.open("GET", requestUrl, true); /* Ant Galio does not support synchronous */
this.debug("-- send");
xmlhttp.send();
I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.
Thanks!
yes, you can
function getFile(url) {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("GET", url, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var fileFromServer = getFile('http://somedomain.com/somefile.txt');
w3c definition http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
client . open(method, url [, async = true [, user = null [, password = null]]])
You can't. There is no "active waiting" in JavaScript, there can be only one active execution a time ("single-threaded").
There is a workaround.
Instead of using the the blocking while loop for poll use the nonblocking setInterval()..
so your code might look something like this.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ");
that.debug('-- ResponseText: "'+data+'"')
}
}
}
//Polling function
function checkEvent(){
if(ajaxFinished == true){
//your code i.e xmlhttp.open("GET", requestUrl, true);
}
clearInterval(chkeventid);//Clear Interval via ID for single time execution
}
var chkeventid=self.setInterval("checkEvent()",100);//The poll call
The setInterval method is treated a bit differently in JS as you know so you may use it as against the while loop.

Categories