Check if no Internet Connection - Popup - Windows 10 App(Javascript) - javascript

Hello,
i searching around the internet, and can't find a full "tutorial", how to write a code, that's if no internet connection automatically shows a error message. I started with the Visual Studio to create a Windows 10 App with Javascript. I searched around, and found some examples with jQuery or AJAX on stackoverflow, but seem's not working for my application. Can someone share a code, that i can put in my application?
I creating a app for my Website, with some addition features, and it's need's internet connection.
Thanks

you can use the NetworkConnectivityLevel, NetworkInformation.getInternetConnectionProfile and getNetworkConnectivityLevel to do this, and show the information with a MessageDialog in the default.js like this:
var connections = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile();
if (connections != null) {
var networkConnectivityLevel = connections.getNetworkConnectivityLevel();
if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Internet access OK.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.constrainedInternetAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Limited internet access.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.localAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Local network access only.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.none) {
var msg = new Windows.UI.Popups.MessageDialog("No internet access.");
}
msg.showAsync();
} else {
var msg = new Windows.UI.Popups.MessageDialog("No internet access.");
msg.showAsync();
}

$.get('/').fail(function(){
//request failed for some reason. probably internet down
console.log("your internet is down");
});

You can use some HTTP test service as follows:
<html>
<body>
<div id="status" style="width:100px;height:40px;"></div>
<script>
function GetConnectionStatusToElement(element) {
var request = new XMLHttpRequest();
request.open("GET", "https://httpbin.org/", true);
request.onload = function () {
element.innerHTML = "Connected";
};
request.onerror = function () {
element.innerHTML = "Not Connected";
};
request.send();
}
GetConnectionStatusToElement(document.getElementById("status"));
</script>
</body>
<html>

Related

How to ping ip address from java script [duplicate]

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Trouble querying Solr from JavaScript and displaying results, getting nothing

I am trying working off of https://wiki.apache.org/solr/SolJSON tutorial. I have put my url for solr in the code, copied from solr admin query result to make sure the query should return something.
I try typing in "title:Asian" into text box (that field/search term combo returned results in the admin console query) but when the button is hit, textbox just clears and nothing in output spot.
I used the dev tools from [F12] key of browser to check console and see there was no errors given there, such as for syntax, so not due to that.
Perhaps I am understanding how the url for query works or should be here? If I leave out local host part as shown I just get error for not specifying local full path.
Does anyone see anything wrong here, or have any ideas/tips of what more to do to try and solve the issue?
[ If I must do/add anything else to make good/better post here, please do explain so I can fix :) ]
<html>
<head>
<title>Solr Ajax Example</title>
<meta charset="UTF-8">
<script language="Javascript">
// derived from http://www.degraeve.com/reference/simple-ajax-example.php
function xmlhttpPost(strURL)
{
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) { // Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
};
var params = getstandardargs().concat(getquerystring());
var strData = params.join('&');
self.xmlHttpReq.send(strData);
//document.getElementById("raw").innerHTML = strData;
return false;
}
function getstandardargs() {
var params = [
'wt=json'
, 'indent=on'
, 'hl=true'
];
return params;
}
function getquerystring() {
var form = document.forms['f1'];
var query = form.query.value;
qstr = 'q=' + escape(query);
return qstr;
}
// this function does all the work of parsing the solr response and updating the page.
function updatepage(str)
{
document.getElementById("raw").innerHTML = str;
var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
var html = "<br>numFound=" + rsp.response.numFound;
var first = rsp.response.docs[0];
html += "<br>product name=" + first.name;
var hl = rsp.highlighting[first.id];
if (hl.name != null) { html += "<br>name highlighted: " + hl.name[0]; }
if (hl.features != null) { html += "<br>features highligted: " + hl.features[0]; }
document.getElementById("result").innerHTML = html;
}
</script>
</head>
<body>
<form name="f1" onsubmit='xmlhttpPost("http://localhost:8983/solr/myCore/select?")'>
<p>query: <input name="query" type="text">
<input value="Go" type="submit"></p>
<div id="result"></div>
<p/><pre>Raw JSON String/output: <div id="raw"></div></pre>
</form>
</body>
</html>

Ajax call with javascript fails with internet explorer

OK here is my code which i am using to call a remote site for a list of data objects which i want to display on another site.
This works fine with Chrome and Firefox but throws error in IE "Permission denied"
I also added the request for Access-Control-Allow-Origin and headers but the issue persist in IE....
I can't use jQuery because the site on which I'll put this might not have jQuery. Does it have to something with cross domain request?
<script id= "sc1" type="text/javascript">
function ajaxRequest() {
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject) {
for (var i = 0; i < activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
} catch (e) {
}
}
} else if (window.XMLHttpRequest) return new XMLHttpRequest()
else return false;
}
var contentDiv = document.createElement("div");
contentDiv.id = 'contentJobsoid';
document.getElementById('sc1').parentNode.appendChild(contentDiv);
(function(){
var mygetrequest = new ajaxRequest()
if (mygetrequest.overrideMimeType) mygetrequest.overrideMimeType('text/html')
mygetrequest.onreadystatechange = function () {
if (mygetrequest.readyState == 4) {
if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1) {
var data = mygetrequest.responseText;
document.getElementById("contentJobsoid").innerHTML = data;
} else {
console.log("An error has occured making the request");
}
}
}
mygetrequest.open("GET", "http://www.demo.com/demo/dee0c7fe-867d-408d-a00f-d9bed4b169a7", true);
mygetrequest.send(null);
return false;
}());
</script> -->
I just passed the data from the server in form of string in the script src tag and it solved my problem very easily

Function can be bypassed by page refresh

I've searched for hours to get a solution for my problem. But I have to ask the community now. I've programmed an ajax file upload system. Here is the Javascript:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('fileAvatar');
var data = new FormData();
data.append('ajax', true);
data.append('avatar', fileInput.files[0]);
var request = new XMLHttpRequest();
request.upload.addEventListener('error', function(event) {
alert('Upload Failed');
});
request.addEventListener('readystatechange',function(event) {
if (this.readyState == 4) {
if (this.status == 200) {
var uploaded = this.response.split("|");
// DO SOME ERROR HANDLING IN THIS AREA
if (uploaded[0] == 'upload_success') {
$('.avatarCropImage').attr('src','<?php echo USERFILES;?><?php echo $log_username; ?>/' + uploaded[1]);
$('.cropInput').attr('type',uploaded[2]);
showPopup('cropAvatar');
/************************/
/***** Problem Area *****/
/************************/
} else {
showPopup('errorNotification');
_('popupError').innerHTML = 'Something went wrong. Please try again.';
}
} else {
alert('Error' + this.status);
}
}
});
request.open('POST','<?php echo $url_data; ?>');
request.setRequestHeader('Cashe-Control', 'no-cashe');
request.send(data);
}
window.addEventListener('load', function() {
var submit = document.getElementById('submitAvatar');
submit.addEventListener('click',handleUpload);
});
The file upload works fine and as you can see, after the file was uploaded I push the uploaded image into a popup called cropAvatar.
Then the user has to crop an area to get a thumbnail of his avatar. If he selects an area and clicks on the Crop-Button, the Crop-Function will be run:
function cropImage() {
var top = $('.cropBox').position().top - 3;
var left = $('.cropBox').position().left - 3;
var width = $('.cropBox').width();
var height = $('.cropBox').height();
var src = $('.avatarCropImage').attr('src');
var type = $('.cropInput').attr('type');
var ajax = ajaxObj("POST", "<?php echo $url_data; ?>");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if (ajax.responseText == "") {
$('.buttonClose').click();
$('.avatarImage').attr('src',src);
$('.cropAvatar').css('display','none');
} else {
alert(ajax.responseText);
showPopup('errorNotification');
_('popupError').innerHTML = 'Something went wrong. Please try again.';
}
}
}
ajax.send("action=avatar&top="+top+"&left="+left+"&width="+width+"&height="+height+"&src="+src+"&type="+type);
}
This also works pretty well. The problem now is that the user can bypass the Crop-Function when he reloads the page. Do you have any solution for that?
I also tried to fix this problem by entering the following code into the Problem Area:
// cropImage() is the Crop-Function
window.unload = cropImage();
Thanks for helping.
Don't save the avatar until the user has done the cropping step.
Leave the file as a dangling temp file until the user has completed the whole upload wizard.
I can come up with a similar scenario:
When you paste a link into a Facebook post, Facebook will give you a thumbnail image for the link. What if you then cancel the post? Where does the thumbnail go, or actually, where has it been since there was no post yet? It's all in a temporary structure until you commit, ie. complete the post.

Javascript: simple xml request

I am learning this stuff so my code might not be pretty... but would appreciate some help :)
I have not written the following code but got it from somewhere else off the web:
function text_xml()
{
realXmlUrl="http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
}
function response_xml()
{
if (self.http_request.readyState == 4)
{
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseText);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
And the error I am getting is:
Error: xml.getElementsByTagName is not a function
What am I doing wrong?
responseText is a string, not an XML. Are you looking for responseXML?
Update
If your script is loaded from a different domain than the XML document you're loading (http://jumac.com/del_me_fruits.xml), then XMLHttpRequest will act differently depedning on the browser.
On IE 8, it will pop up a warning window complaining that "The page is accessing information that is not under its control. This poses a security risk. Do you want to continue?" if you click yes, then it will work correctly (i.e., the XML will load and the alerts for the fruits will be displayed).
On Chrome 12, however, it doesn't pop anything and it will say that "XMLHttpRequest cannot load http://jumac.com/del_me_fruits.xml. Origin http://localhost:54671 is not allowed by Access-Control-Allow-Origin." Because of this error, the responseXML property of the request object will be null and you'll see the error you have.
There are other questions regarding cross-domain XMLHttpRequest where you may find how to solve your issues, such as Cross-site XMLHttpRequest and http://code.google.com/chrome/extensions/xhr.html.
<body>
<script type="text/javascript">
function text_xml() {
realXmlUrl = "http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML; // this doesn't have anything
}
function response_xml() {
if (self.http_request.readyState == 4) {
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseXML);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
</script>
<input type="button" value="Click me" onclick="text_xml();" />
<p><div id="ex"></div></p>
</body>
I usually love using a dictionary when working with any kind of transferring data across servers.
MkNxGn.pro provides a sleek way to make XML HTTP requests via MkNxGn Proquest.
Load Proquest, This can be separate from the code<script src="https://mknxgn.pro/scripts/Proquest_Proquest-v1.0.js"></script>
<script>
Proquest("POST",
URL_HERE,
DATA,<br>
HEADERS,
RType,
Ignore JSON errors,
Callback);
</script>
That way you could easily write:
<script>
Proquest("GET", "http://jumac.com/del_me_fruits.xml", Skip, {'Content-type': 'text/xml'}, 'response', false, function(resp) {
resp.overrideMimeType('text/xml'); //Looks like you want it to be XML if its not.
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(resp.responseXML);
});
</script>
ignoring jason's edit to rewrite it better.
Consider using a javascript libary like jquery.
jquery ajax is pretty much self explaining and you don't have to mess with brower compatibility. http://jquery.com/

Categories