How to abort XMLHttpRequest if the connection timeout? - javascript

I'm experiencing an issue with XMLHttpRequest. If there is no Internet connection, my request is not timing out and thus freezing the browser. Here is the request code:
var jsonData = new XMLHttpRequest();
jsonData.open('GET', urltest, false);
jsonData.Timeout = 100;
jsonData.send(null);
if(jsonData.status == 200) {
alert(jsonData.statusText);
}else{
alert(jsonData.statusText);
}
How do I abort the request if the server doesn't respond?

I made some changes to your code, and I left some comments where I made changes explaining what's going on. I hope it helps!
var jsonData = new XMLHttpRequest();
jsonData.open('GET', urltest);/* I removed the false, because it kept the browser
waiting for the page to load to continue, and it didn't let it do other things
while it was still loading.*/
jsonData.Timeout = 100;
jsonData.send();
jsonData.onreadystatechange = function() {/*Each time readyState changes value,
run this code.*/
if (jsonData.readyState == 4) {/*When readyState is equal to 4,
the page has fully loaded.
Only run the code when it's 4,
not when it's still loading.*/
if (jsonData.status == 200) {
alert(jsonData.statusText);
} else {
alert(jsonData.statusText);
}
// More things to do when the page has fully loaded...
}
}

Related

XMLHttpRequest sends url as response text, Firefox doesn't redirect

I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support

can xmlhttpRequest response wait even after onload

I am loading a page through xmlHttpRequest and I am not getting one variable which come into existance after some miliseconds when page loading is done
so the problem is when xmlHttpRequest sends back the response I do not get that variable in it.
I want it to respond back even after onload.
var xhr = new XMLHttpRequest();
xhr.open("GET", event.url, true);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() { callback(); };
xhr.followRedirects = true;
xhr.send();
I tried setTimeOut but of no use because may be at that time call is finished
xhr.onload = function() {
console.log('wait for response');
setTimeout(function(){
callback(xhr.responseText);
},2000);
};
I tried readyStateChange , but no success
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
callback(xhr.responseText);
};
};
by the way, I am trying to load amazon signIn page
and the variable which is missing everytime is hidden Input Field metadata1,
I get all other hidden Input fields in response text , except input field, named "metadat1"
I'll be more than Happy, If anyone can help.
Thanks in advance
ohh Finally I did it,
I din't read any javascript, Instead I just extracted scripts which I received in xhr calls and executed it inside a hidden div, and here it is , I got that variable's value
abc(xhr.responseText);
function abc(xhrRes){
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrdiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var scr = document.getElementById('xhrdiv').getElementsByTagName("script");
//5 scripts needed to generate the variable
for(i=0;i<5;i++){
eval(scr[i].innerHTML);
if( i+1 == 5){
var response = document.getElementById('xhrdiv').innerHTML;
return response; //and in this response variable I have every thing I needed from that page which I called through xmlhttp Req
}
}
}
---------------------Improved Version-----------------------
Instead of executing script through eval,
keep script content in a file AND Include it, as we normally include the script, that works better.
xhrRes = xhr.responseText;
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrDiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var xhrDiv = document.getElementById('xhrDiv');
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = JSfile;
xhrDiv.appendChild(newScript);
(it shows the edit is done my anonymous user, :( because I forgot to Login, while editing)
If the data doesn't exist until some time after the page has loaded then, presumably, it is being generated by JavaScript.
If you request the URL with XMLHttpRequest then you will get the source code of that page in the response. You will not get the generated DOM after it has been manipulated by JavaScript.
You need to read the JavaScript on the page you are requesting, work out how it is generating the data you want to read, and then replicate what it does with your own code.

Control skips the ajax object onreadystatechange function. why?

I'm new to web-development. Created a signup page making some asynchronous calls to php. Ran debugging found the control skips the onreadystatechange function completely. Please help...
var ajax = ajaxObj("POST", "signup.php"); //defines the ajax object, definition is below
ajax.onreadystatechange = function () { //doesn't run after this line
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box
at <u>"+e+"</u> in a moment to complete the sign up process.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); //control reaches here directly
}
}// control exits here
The ajax object is created externally here..
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is because it's an event callback function and it will be called when server responds to your ajax request. If you're using firefox press F12, switch to network tab and check html and xhr to see it's status.
Because it is asynchronous so the function won't be called as you step through the code in a linear fashion.
It gets called by native code when the ready state changes.
Stick a breakpoint inside the function if you want to debug it.

Ajax - browser lag when updating content

I'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).

How to check for internet connection without having to refresh my whole page

I want the following function to be called every x seconds, so I don't have to refresh my page.
var rq = new XMLHttpRequest();
rq.open('GET', "SAME DOMAIN ADDRESS", true);
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
clearTimeout(xmlHttpTimeout);
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
}
}
};
rq.send("");
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
rq.abort();
// IF no internet connection found, call this whole javascript function/code AGAIN in 5 seconds! to check for internet connection
}
Basically, I want to check for internet connection without having to refresh my whole page - and if there is, then redirect to Tracker.html
Check if navigator.onLine is true or false.
The best approach is to use setTimeout:
function callMe() {
// Some Code
setTimeout(callMe, 1000);
}
callMe();
Your code will look like that:
var rq = new XMLHttpRequest();
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
setTimeout(rq.send, 5000);
}
}
};
rq.send();
If you want to check if the client is connected you can also use the new online and offline events described here.
An ajax solution will only work on the same domain. However on the same domain you will probably not need to test whether the server is online. With navigator.onLine it will indicate whether the internet is accessible however still the appropriate server can be unreachable.
The trick is to try to load an image of the target server and on error then retry after 5 seconds. And when the image has been loaded successfully then a redirect could be done.
<html>
<header>
</header>
<body>
<script type="text/javascript">
var img = new Image();
var ping = function() { img.src = "http://www.somedomain.com/valid_image.jpg"; }
ping();
img.onerror = function(e) {
console.log('error');
setTimeout(function() {
ping();
}, 5000);
}
img.onload = function(e) {
console.log('YES');
window.location.href = "http://www.google.com";
}
</script>
</body>
</html>

Categories