How do I check If there is internet connection with javaScript? [duplicate] - javascript

This question already has answers here:
Check if Internet Connection Exists with jQuery? [duplicate]
(9 answers)
Closed 8 years ago.
I'm making an app with XDK, so I need to show a connection failure message. I want to check that with a button that when I click on it check the connection and if it's online goes to a webpage, otherwise goes to another with the failure connection message.
Is there any solution, method or function with javaScript or jQuery for do this status check?

Any xhr request to your server should do the trick. If it comes back with a timeout, then you know you don't have a connection (or that your server isn't working).

Use an XMLHttpRequest to query any file, if it succeeds you are connected else you ain't.
function checkConnection(){
var xhr = new XMLHttpRequest();
var file = "http://yoursite.com/somefile.png";
var r = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?subins=" + r, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}

Related

Javascript - Check if (URL)-file exists over HTTPS

I already tried getting the file with this Code, the problem is, the code works with http requests but not with https request (which is what i need)
function isThere(url) {
var req = new XMLHttpRequest(); // XMLHttpRequest object
try {
req.open("HEAD", url, false);
req.send(null);
return req.status == 200 ? true : false;
} catch (er) {
return false;
}
}
function setUser() {
var user = document.getElementById("userName").value;
if (isThere("https://dev.sentinex.de/ulogv2/" + user) == true) {
alert("File exists!");
} else {
alert("File doesn't exist!");
}
}
Does anyone know how i can change the code to work with HTTPS Requests or how i could rewrite it so that i could get HTTPS Requests?
PS: I am just requesting from my own domain - so no other domains for requests are needed.
Please posts the domain of the resource that executes the code.
If you are on Http. You must use a bypassSecurityTrust

Raw javascript eq of ajax post is not working correctly [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 7 years ago.
I am trying to make some ajax post raw js script and I am using one of the questions asked here in stackoverflow but I encountered a problem.
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send("prize=" + prize);
return false;
When I check in chrome network the payload is sent correctly prize=632 but the result of the php script with $_POST['prize'] is empty. Where can the problem be?
Best regards!
You are missing the headers:
var data = "prize=" + prize;
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
// Send the expected headers information along with the request
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", data.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send(data);
return false;

JQM - How to get dynamic data when page loads using XMLHttpRequest? [duplicate]

This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I use pageinit to load page. I call an XMLHttpRequest to send and get request to PHP programs on Linux, using RESTful API on server side. The server side accept an array I send to it and echo an JSON back. It all work well. However, HTTP_GET functions returns back to page and displays content before it finished and got a response from server.
How can I prevent it from going back before it responded?
pageinit
$(document).on("pageinit","#quote_open1",function(){
alert('pageinit quote_open1');
openPage(); });
openPage
function openPage(url, jsontest){
var jsonResponse=HTTP_GET( url, jsontest);
alert('!!!!!!!!!!!!!!!!-->'+jsonResponse);
}
HTTP_GET
function HTTP_GET( url, jsonToSend){
alert('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url+"jsonToSend",true); //open server connection
xhr.send();//this is where json string will be sent out
//
//this function send
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
alert(xhr.readyState);
jsonResponse=xhr.responseText;
alert("!!!jsonResponse="+jsonResponse);
alert("!!!xhr.responseText"+xhr.responseText);
return "server returned a response 1"; //RETURNS this all the time
}
};
alert('END HTTP_GET');
if (xhr.readyState == 4) return "server returned a response 2"; //want to return this when leaves this function
return "stil in progress returns before it's finished";
};
(this 3 functions are in different js)
Thanks.
what you miss here is the fact that xhr is asynchrone, so your function HTTP_GET returns before the request is done.
You could use a callback function like this :
$(document).on("pageinit","#quote_open1",function(){
console.log('pageinit quote_open1');
openPage(); });
function openPage(){
var doTheJob = function(jsonResponse){ console.log('jsonResponse : '+jsonResponse); }
HTTP_GET( url, doTheJob);
}
function HTTP_GET( url,callBackFunc){
console.log('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url,true); //open server connection
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
callBackFunc(xhr.responseText);
}
};
xhr.send();//this is where json string will be sent out
//
console.log('END HTTP_GET');
};

check if network connection exists in javascript [duplicate]

This question already has answers here:
Check if Internet Connection Exists with jQuery? [duplicate]
(9 answers)
Closed 9 years ago.
I want to check if network connection exists at runtime in javascript. I am using window.navigator.onLine but its not working.
<script language="javascript">
alert(window.navigator.onLine);
</script>
it is returning true always
You could try using an AJAX call with a short timeout and handling the success/error.
You can do it as below :
if (navigator.onLine) {
alert("online");
}
or as below :
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);
function state_change(){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log('worked');
} else if(xhr.status == 0) {
console.log('no internet');
} else {
// Some other error
}
}
}

ajax success called before request has finished

at my whits end with this...
The problem I have is that around the same time (roughly 60-70 mins through the request) the success function is called for the ajax request, but the tomcat logs prove that the request is still running.
(perspective: the request is supposed to either return an empty string ("") or a html page (of errors) however when the success function is called, it returns a string of length 2 result = " " (2 white space characters)
I cannot get this to reproduce in chrome, only IE (which is a problem as we cater specificity for IE)
At first I though it was a jQuery issue as I have multiple polls running when the request is sent (to update jQuery progress bar info)
However...
When I test this with just one asynchronous ajax request (not jQuery) that calls a Java method that just loops for 3 hours printing out in the log each second, it always calls success around the 3600 second mark (still another 7200 seconds remaining).
Example code:
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/text');
}
}
else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!http_request) {
alert('Giving up: Cannot create an XMLHTTP instance');
return false;
}
url += "&random=" + Math.random();
http_request.open('GET', url, true);
http_request.onprogress = function () { };
http_request.ontimeout = function () { };
http_request.onerror = function () { };
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
alert("success: ("+result.length+") ["+result+"]");
}
}
};
NOTE: this is not a time-out error (at least not an ajax one) as the ajax time-out options seem to work correctly and return time-out errors accordingly, but as I have said, its not a time-out error...the success function is called too early.
Hope somebody can help :)
Cheers,
Steve.
Update:
I've run the request with the network tab capturing and it shows that the result was aborted: here
Thanks #ArunPJohny, this has given me a new direction to look in. Is there some kind of "onAbort" ajax callback? As I would have thought this kind of response would be caught by the "error:" callback
Update 2:
I have since found my way to a number of SO topics, more notably: xmlhttprequest timeout / abort not working as expected?
Tim provides some useful links for catching the abort, but still no clue as to why its getting aborted.
follow-on: here

Categories

Resources