check if network connection exists in javascript [duplicate] - javascript

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

Related

Using a json value as a global variable in a script outside of a function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 months ago.
I can't find a way to use the value obtained from the JSON function from ipify.org.
I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.
I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/
<script type="text/javascript">
function getIP(json) {
window.ipa = json.ip;
}
alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.
You also need to attach this function call to an event (I used "onload" bellow).
Example:
function xhrget(items, route, callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', route);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = 1000;
xhr.send(encodeURI(items));
xhr.ontimeout = function(e){
callback('404');
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
if(xhr.status >= 500 && xhr.status < 600){
callback('An error occurred, please wait a bit and try again.');
}
if(xhr.status === 404) {
callback('404');
}
};
}
function getIP() {
xhrget(null, "https://api.ipify.org", (ip) => {
console.log(ip);
window.ipa = ip;
alert(window.ipa); //return "undefined"
});
}
window.addEventListener('load', (event) => {
getIP();
});

Perform $.getJSON without using JQuery [duplicate]

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 6 years ago.
How do I get country code using javascript only, I am not allowed to use jQuery.
I have seen some sites like http://ipinfo.io , but all examples uses JQuery getJson, can I implement the same method :
var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
country_code = data.country;
alert(country_code);
});
I tried the following, but it returns a page instead:
var request = new XMLHttpRequest();
request.onload = function(elements) { console.log(elements); };
request.open("get", "http://ipinfo.io", true);
request.send();
Working example:
var someIp = '8.8.8.8';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "//ipinfo.io/"+someIp+"/json", true);
xmlhttp.send();
<div id="myDiv">
pending
</div>
The ipinfo.io service returns JSON format only when proper header requesting JSON is attached. But it can be specified easily also with the /json directly in the requesting url.

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;

How to return to the function calling the current function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
How to return to the calling function (the function above). I would like to return true if the file exists when doing UrlExists('file.png') :
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, true);
http.onerror = function(e){
//console.log('......onerror: ' + JSON.stringify(e));
if (typeof e !== 'undefined'){
return false
}
};
http.send();
return http.onerror();
}
Use XMLHttpResponse as async. Because async responses may not be received in the order that they are requested and since you may be checking for multiple files it may be a good idea to check the responseURL property before acting on the case where the file does not "exist" (is not found or returns error, etc.)
jsFiddle example: http://jsfiddle.net/5f42L6nz/4/
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
function UrlExists(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true); // true => async request
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// URL found, do stuff for "exists"
alert("url exists:\r\n" + xhr.responseURL);
} else {
// URL not found, could check xhr.status === 404, etc.
// do stuff when URL not found, but no exception/error thrown
alert("not found or unexpected response:\r\n" + xhr.responseURL);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");

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

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

Categories

Resources