Related
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...
I have a method WCF, which returns a JSON:
enter image description here
the client has a script that should take the data from the wcf service
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories',
method: 'get',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success:function(data)
{
alet(data.Announcing[0].Categories.id);
},
error: function (error)
{
alert(error);
}
})
var request = createCORSRequest("get", "http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories");
request.send();
})
})
</script>
<input id="btn" type="button" />
After click button i have this error: Object object
and i have console message:
SCRIPT7002: XMLHttpRequest: Network error 0x80070005, Access Denied .
SEC7120: Source http: // localhost: 4945 is not found in the header Access-Control-Allow-Origin ..
How to solve these problems?
Well, because your web server is running locally (see the 192.168...) address, I can't test it, but your error messages tell me the following:
The first one indicates that you are trying to access an unavailable resource. Try visiting the url with your browser, and see if that gives a response. Also in, http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories, the double slash might indicate it's the wrong url.
The second error is not complete, but are you maybe serving the web page from a different server than the api? Because a quick google search reveals that it has something to do with a cross-site request.
I am working on a browser extension using crossrider. I need to send some data from popup to extension.js
My code of popup
<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
/************************************************************************************
This is your Popup Code. The crossriderMain() code block will be run
every time the popup is opened.
For more information, see:
http://docs.crossrider.com/#!/api/appAPI.browserAction-method-setPopup
*************************************************************************************/
function crossriderMain($) {
// var to store active tab's URL
var activeTabUrl = null;
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') activeTabUrl = msg.url;
});
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
alert(activeTabUrl);
// THE REST OF YOUR CODE
}
</script>
</head>
<body>
Hello World
</body>
</html>
Code of Extension.js
appAPI.ready(function($) {
// Message listener
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url')
// Send active tab's URL to popup
appAPI.message.toPopup({
type: 'active-tab-url',
url:encodeURIComponent(location.href)
});
});
// THE REST OF YOUR CODE
});
The value of activeTabUrl is not getting updated. It gives NULL value.
P.S : I am able to communicate between background.js and popup. But for some reason appAPI.message.toActiveTab function is not working for me. Where I am doing the mistake?
Background.js (Edit)
var tabUrl='';
/* appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
}); */
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
});
var dataString = '{"url":"'+tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
alert(dataString);
appAPI.request.post({
url: 'REST API URL',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
Working code of Background.js
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
var dataString = '{"url":"'+tabInfo.tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
// alert(dataString);
appAPI.request.post({
url: 'http://fostergem.com/api/bookmark',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
});
In this code sample, the activeTabUrl variable is only set once a response is received from the extension.js file since the messaging is asynchronous by design. Hence, when calling alert(activeTabUrl); in the code, the message has not yet been received back fro the extension.js code thus the value is still null as it was initialized.
To use the activeTabUrl variable you must wait for the mesage from the extension.js file, and hence you should place the code using the variable in the callback of the message listener, preferably as a function. Also note that using an alert in the popup code causes the popup to close and should hence not be used in the popup scope.
I tested the following popup code, which does away with the variable to avoid confusion and passes the active tab URL as a parameter to the function called in the message listener, and it worked as expected:
function crossriderMain($) {
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') ShowPageUrl(msg.url);
});
function ShowPageUrl(url) {
$('#page-url').html('<b>Page URL</b>: ' + url);
}
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
//alert(activeTabUrl);
// THE REST OF YOUR CODE
}
[Disclaimer: I am a Crossrider employee]
I have a link: Hello.
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.
Here's some code that would accept a full URL and use YQL to detect if that page exists:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes, or request succeded
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
Based on the documentation for XMLHttpRequest:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
If you are happy to use jQuery you could do something like this.
When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
You won't be able to use an ajax call to ping the website because of same-origin policy.
The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.
Example:
function pingImgOnWebsite(url) {
var img = document.createElement('img');
img.style.visibility = 'hidden';
img.style.position = 'fixed';
img.src = url;
img.onerror = continueBtn; // What to do on error function
document.body.appendChild(img);
}
Another way to do this is is with PHP.
You could add
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
<a href="<?php echo $url; ?>Link</a>
I have some Javascript JQuery code that does an Ajax call to the server every 5 mins, it's to keep the server session alive and keep the user logged in. I'm using $.ajax() method in JQuery. This function seems to have an 'error' property that I'm trying to use in the event that the user's internet connection goes down so that the KeepAlive script continues to run. I'm using the following code:
var keepAliveTimeout = 1000 * 10;
function keepSessionAlive()
{
$.ajax(
{
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
success: function(data)
{
alert('Success');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
}
});
}
When I run it, I'll get 'Success' popup on the screen in an alert box every 10 seconds which is fine. However, as soon as I unplug the network cable, I get nothing, I was expecting the error function to get called and see a 'Failure' alert box, but nothing happens.
Am I correct in assuming that the 'error' function is only for non '200' status codes returned from the server? Is there a way to detect network connection problems when making an Ajax call?
// start snippet
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
}
else {
// something weird is happening
}
}
//end snippet
You should just add: timeout: <number of miliseconds>, somewhere within $.ajax({}).
Also, cache: false, might help in a few scenarios.
$.ajax is well documented, you should check options there, might find something useful.
Good luck!
Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:
$.ajax({
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
timeout: 15000,
success: function(data) {},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
})
JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.
What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:
function handleError(jqXHR, textStatus, errorThrown) {
...
}
jQuery.ajax({
...
success: function(data, textStatus, jqXHR) {
if (data == "") handleError(jqXHR, "clientNetworkError", "");
},
error: handleError
});
If you are making cross domain call the Use Jsonp. else the error is not returned.
USE
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
(more code below - UPLOAD IMAGE EXAMPLE)
var selFoto = {
foto: null,
upload: function(){
LoadMod.show();
var arquivo = document.frmServico.fileupload.files[0];
var formData = new FormData();
if (arquivo.type.match('image.*')) {
formData.append('upload', arquivo, arquivo.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
xhr.responseType = 'blob';
xhr.onload = function(e){
if (this.status == 200) {
selFoto.foto = this.response;
var url = window.URL || window.webkitURL;
document.frmServico.fotoid.src = url.createObjectURL(this.response);
$('#foto-id').show();
$('#div_upload_foto').hide();
$('#div_master_upload_foto').css('background-color','transparent');
$('#div_master_upload_foto').css('border','0');
Dados.foto = document.frmServico.fotoid;
LoadMod.hide();
}
else{
erroUploadFoto(XMLHttpRequest.statusText);
}
if (XMLHttpRequest.readyState == 4) {
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
};
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
xhr.send(formData);
}
else{
selFoto.erroUploadFoto('');
MyCity.mensagens.push('Selecione uma imagem.');
MyCity.showMensagensAlerta();
}
},
erroUploadFoto : function(mensagem) {
selFoto.foto = null;
$('#file-upload').val('');
LoadMod.hide();
MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
MyCity.showMensagensAlerta();
}
};
here's what I did to alert user in case their network went down or upon page update failure:
I have a div-tag on the page where I put current time and update this tag every 10 seconds. It looks something like this: <div id="reloadthis">22:09:10</div>
At the end of the javascript function that updates the time in the div-tag, I put this (after time is updated with AJAX):
var new_value = document.getElementById('reloadthis').innerHTML;
var new_length = new_value.length;
if(new_length<1){
alert("NETWORK ERROR!");
}
That's it! You can replace the alert-part with anything you want, of course.
Hope this helps.
Have you tried this?
$(document).ajaxError(function(){ alert('error'); }
That should handle all AjaxErrors. I´ve found it here.
There you find also a possibility to write these errors to your firebug console.