How can I stop jQuery.ajax() from logging failures to the console? - javascript

I am using the following jQuery JSONP request to check the status of a resource by URL. When the resource is not available or the server is down, my ajaxFail() function updates the display.
function fetchServerStatus(service, host)
{
var port = serverStatus[service].port;
$.ajax({
url: "http://" + host + ":" + port + "/admin/server/status",
dataType: "jsonp",
timeout: 1000,
error: ajaxFail,
fail: ajaxFail,
success: ajaxDone,
done: ajaxDone,
complete: ajaxAlways,
always: ajaxAlways
});
}
The problem I'm having is that despite declaring handlers for fail and error, which do not log anything to the console, jQuery always logs the failed request in the console. If the resource is unavailable for a long time, this builds up a huge console log, eventually crashing the browser process (Chrome in my case).
Is there any way to stop it from doing this?

The logging entry in chrome's console is a behaviour of chrome when any HTTP request is handled, not a problem with jQuery or ajax(XMLHttpRequest), even an <img> or <link> tag could cause this issue.
Your only choice is to fix your server-side code not to trigger an error for ajax (eg. 404 not found or wrong content-type), so based on the content logged to console, maybe a better solution could be found, please provide accurate logging message in your console.

put this in the top of your page:
<script>
$(document).ready(function() {
jQuery.migrateMute = true;
})
</script>
its temporary - but worked for me. Beats having to scroll through 45 lines of nonsense to debug js errors.

Related

jQuery Ajax Unexpected token < error on 404 instead of normal ajax error handler function

When using the jQuery Ajax function, when specifying error and success handlers, you would expect invalid files and 404 errors to be caught by the designated error handler function, but for some reason my code does not.
Code:
// using jQuery 3.4.1
// this code has been taken from a larger function, but the issue can be replicated by pasting
// the following code into the JS Console.
var scriptPath = 'http://mywebserver.localhost/application/invalid.js';
jQuery.ajax( {
async: false,
type: 'GET',
url: scriptPath,
crossOrigin: false,
data: null,
global: false,
cache: true,
success: function() {
debugger;
// do some stuff
onResult();
},
error: function( jqXHR, textStatus, errorThrown ) {
debugger;
Lib.showNetworkErrorAlert( jqXHR, textStatus, errorThrown );
},
dataType: 'script'
} );
This results in:
Uncaught Error From: ~unknown~
Error: Uncaught SyntaxError: Unexpected token '<' in:
http://mywebserver.localhost/........ line: 1
Just to clarify, I have looked at the SO questions out there already, but the ones I found tended to focus on the cause of the error. I know what the error 'Unexpected token < in ...' is, its simply JS trying to parse the target as JS, but instead its given a 404 error html file, so the < from the first tag triggers the error.
What I am trying to find out and understand, is why this error appears instead of the normal error handler that is specified. At the very least I would have thought setting the dataType to script would make it give a slightly better error to realise, hey this is a HTML 404 error file, not a script.
Any help and insight greatly appreciated.
Update: Here's the Network tab from Dev Tools showing it is returning a 404.
Turns out this is actually a bug in jQuery - rather than me using it incorrectly - which was reported back in 2018, but the fix was only earmarked for inclusion in jQuery 4.0.0.
However that might be a while away, so I have now reported the bug again for inclusion in more current versions, and the admins have since discussed this and decided to include it as a fix in 3.5.0.
Explanation of the bug
Normally, using the dataType:script attribute tells jQuery's Ajax function "I'm supplying a script, please execute the JavaScript once it has loaded."
The problem was that regardless of the response status code, the file (or whatever was returned) would be evaluated as JavaScript (even if not JavaScript), which of course is going to cause errors if a 404 error returns a 404 Error HTML page.
The solution to this can be seen on Github (Just so I dont explain it incorrectly here), but in simple terms it should no longer execute scripts for unsuccessful HTTP responses.

How to get callback error to alert in JavaScript?

I am building app with PhoneGap. It working fine on my PC. But when I installed it as android app it did not work. It fire alert('Oppps...something went wrong').
I have following code...
function getFloors(url, callback){
var data = $.ajax({
type: 'GET',
url: "http://example.com/all_test/get_floors.php"
}).done(callback).error(function(e){
alert('Oppps...something went wrong')
});
return data;
};
Let assume there is no page like http://example.com/all_test/get_floors.php.
Then you can find error in console like GET http://example.com/all_test/get_floorss.php 404 (Not Found).
I need to display that error as alert. I mean I need to print real error instead of alert('Oppps...something went wrong'). So I can find what is issue in mobile.
How should I get that error (what display on the console) for a alert.
Look at this documentation
http://api.jquery.com/jQuery.ajax/#jqXHR
the e on error(function(e) returns a jqXHR object which returns following properties that you can print at your disposal
readyState
responseXML and/or responseText - when the underlying request responded
with xml and/or text, respectively
status
statusText
I think you are trying to find the e.responseText or e.responseXML

Sinatra not recognising javascript for session

I'm trying to log into a Sinatra app with jQuery, but Sinatra is just not seeming to recognise it at all for some reason, here is my code to see if the user is logged in:
Sinatra app:
get '/logged_in' do
if session[:logged_in] == true
status 200
"OK"
else
status 200
"False"
end
end
When I browse to /logged_in in my browser, I see OK, but when I execute the following Javascript, I get False printed to the console - seems bizarre to me.
var r = $.ajax({
type: "GET",
url: "http://xxx-xxx.com/logged_in"
});
r.success(function(msg) {
console.log(msg);
});
Any insight would be appreicated!
It would be good if you could give more details. (Browser, chronological request log including HTTP status codes, or even a dump from wireshark.) However here is my guess:
var r = $.ajax({
cache: false,
type: "GET",
url: "/logged_in",
success: function(msg) {
console.log(msg);
}
});
Some browsers aggressively cache AJAX requests, in particular GET requests. So you may want to try cache: false. Adding the success function later also seems odd to me, I have never seen that in any code.
Edit: Is the server answering the AJAX request on the same domain? (The domain must be the same as in your browser test.) Usually it should not be necessary to specify the domain inside the URL, so I removed it in the code here. So after all it might be a problem due to the Same Origin Policy.
I would place my bet on this being a jQuery issue rather than a Sinatra issue. Check that the cookie is being sent for the ajax request. There are a number of reasons why the cookie is not getting sent.

Debugging IFrame content

I'm having a problem with a page that works fine by itself, but when it's embedded in a iFrame in a corporate webpage (that I don't control) it chokes in IE9 (but not IE8).
The page uses jQuery to make an AJAX call and KnockoutJS to bind content for display. The page passes parameters in a GET request to my server with responds with AJAX, and it seems that it chokes when getting the data back from the server. The data is correct and correctly formatted, however, when this code executes:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
In IE9, I always hit the "An error occurred..." branch with the errorThrown of "SyntaxError: Invalid character", which tells me nothing.
Anybody got any suggestions on how to go about debugging this problem? I used Fiddler to look at what was being sent to and returned by the server, and everything looks fine on that end.
Update: After sleeping on it for a while, I started fresh today. What I've determined is that for some reason, when my page is iFramed, instead of getting the JSON response:
"{"Foo":true,"Bar":true}"
I'm actually getting (from forcing an error in the error handler so I could inspect the state of the jqXHR.responseText) is:
" {"Foo":true,"Bar":true}"
Which if, using the console, I try feeding to JSON.parse, gives me an error. So the question is, where the heck is that leading space coming from? If I run this in Firefox, I see the correct response from the server (no space) and if I run this outside of the iFrame, I see no leading space. So I don't think it's coming server side. Somewhere in the mess of JS running on the parent page and my page, it's inserting a leading space.
Update 2: A closer examination reveals that jqXHR.responseText.charCodeAt(0) is 65279, so it's not actually a space (although it displays as one) it is the byte order mark. But why is it there now (and not before) and why is it causing a problem?
I couldn't figure out the reason for this problem, so I hacked my way around it by adding a custom converter to my ajax call. So I now have this:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
converters: { "text json": HackyJSONConverter },
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
//alert("Timed out");
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
And my hacky converter looks like this:
function HackyJSONConverter(data) {
if (data[0] = 65279) {
// leading BOM - happens only with an iFrame in OT for some unknown reason
data = data.substring(1);
}
return JSON.parse(data);
}
It's immensely stupid, and I would be delighted if anybody has a better way!

Detect the Internet connection is offline?

How to detect the Internet connection is offline in JavaScript?
Almost all major browsers now support the window.navigator.onLine property, and the corresponding online and offline window events. Run the following code snippet to test it:
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:
Try setting your system or browser in offline/online mode and check the log or the window.navigator.onLine property for the value changes.
Note however this quote from Mozilla Documentation:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.
In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.
(emphasis is my own)
This means that if window.navigator.onLine is false (or you get an offline event), you are guaranteed to have no Internet connection.
If it is true however (or you get an online event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.
I initially intended to post this as an update to Grant Wagner's answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.
You can determine that the connection is lost by making failed XHR requests.
The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.
Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.
Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.
Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.
IE 8 will support the window.navigator.onLine property.
But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.
Until that happens, either XHR or an Image() or <img> request can provide something close to the functionality you want.
Update (2014/11/16)
Major browsers now support this property, but your results will vary.
Quote from Mozilla Documentation:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.
In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.
if(navigator.onLine){
alert('online');
} else {
alert('offline');
}
There are a number of ways to do this:
AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuery documentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
You could put an onerror in an img, like <img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');" />.
This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.
So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.
As olliej said, using the navigator.onLine browser property is preferable than sending network requests and, accordingly with developer.mozilla.org/En/Online_and_offline_events, it is even supported by old versions of Firefox and IE.
Recently, the WHATWG has specified the addition of the online and offline events, in case you need to react on navigator.onLine changes.
Please also pay attention to the link posted by Daniel Silveira which points out that relying on those signal/property for syncing with the server is not always a good idea.
You can use $.ajax()'s error callback, which fires if the request fails. If textStatus equals the string "timeout" it probably means connection is broken:
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
From the doc:
Error: A function to be called if the request
fails. The function is passed three
arguments: The XMLHttpRequest object,
a string describing the type of error
that occurred and an optional
exception object, if one occurred.
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror". This is an Ajax Event
So for example:
$.ajax({
type: "GET",
url: "keepalive.php",
success: function(msg){
alert("Connection active!")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if(textStatus == 'timeout') {
alert('Connection seems dead!');
}
}
});
window.navigator.onLine
is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:
window.addEventListener("offline",
()=> console.log("No Internet")
);
and for checking if online:
window.addEventListener("online",
()=> console.log("Connected Internet")
);
The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3
I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!
I use CodeIgniter and Jquery:
function checkOnline() {
setTimeout("doOnlineCheck()", 20000);
}
function doOnlineCheck() {
//if the server can be reached it returns 1, other wise it times out
var submitURL = $("#base_path").val() + "index.php/menu/online";
$.ajax({
url : submitURL,
type : "post",
dataType : "msg",
timeout : 5000,
success : function(msg) {
if(msg==1) {
$("#online").addClass("online");
$("#online").removeClass("offline");
} else {
$("#online").addClass("offline");
$("#online").removeClass("online");
}
checkOnline();
},
error : function() {
$("#online").addClass("offline");
$("#online").removeClass("online");
checkOnline();
}
});
}
an ajax call to your domain is the easiest way to detect if you are offline
$.ajax({
type: "HEAD",
url: document.location.pathname + "?param=" + new Date(),
error: function() { return false; },
success: function() { return true; }
});
this is just to give you the concept, it should be improved.
E.g. error=404 should still mean that you online
I know this question has already been answered but i will like to add my 10 cents explaining what's better and what's not.
Window.navigator.onLine
I noticed some answers spoke about this option but they never mentioned anything concerning the caveat.
This option involves the use of "window.navigator.onLine" which is a property under Browser Navigator Interface available on most modern browsers. It is really not a viable option for checking internet availability because firstly it is browser centric and secondly most browsers implement this property differently.
In Firefox: The property returns a boolean value, with true meaning online and false meaning offline but the caveat here is that
"the value is only updated when the user follows links or when a script requests a remote page." Hence if the user goes offline and
you query the property from a js function or script, the property will
always return true until the user follows a link.
In Chrome and Safari: If the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other
conditions return true. So while you can assume that the browser is
offline when it returns a false value, you cannot assume that a true
value necessarily means that the browser can access the internet. You
could be getting false positives, such as in cases where the computer
is running a virtualization software that has virtual ethernet
adapters that are always "connected".
The statements above is simply trying to let you know that browsers alone cannot tell. So basically this option is unreliable.
Sending Request to Own Server Resource
This involves making HTTP request to your own server resource and if reachable assume internet availability else the user is offline. There are some few caveats to this option.
No server availability is 100% reliant, hence if for some reason your server is not reachable it would be falsely assumed that the user is offline whereas they're connected to the internet.
Multiple request to same resource can return cached response making the http response result unreliable.
If you agree your server is always online then you can go with this option.
Here is a simple snippet to fetch own resource:
// This fetches your website's favicon, so replace path with favicon url
// Notice the appended date param which helps prevent browser caching.
fetch('/favicon.ico?d='+Date.now())
.then(response => {
if (!response.ok)
throw new Error('Network response was not ok');
// At this point we can safely assume the user has connection to the internet
console.log("Internet connection available");
})
.catch(error => {
// The resource could not be reached
console.log("No Internet connection", error);
});
Sending Request to Third-Party Server Resource
We all know CORS is a thing.
This option involves making HTTP request to an external server resource and if reachable assume internet availability else the user is offline. The major caveat to this is the Cross-origin resource sharing which act as a limitation. Most reputable websites blocks CORS requests but for some you can have your way.
Below a simple snippet to fetch external resource, same as above but with external resource url:
// Firstly you trigger a resource available from a reputable site
// For demo purpose you can use the favicon from MSN website
// Also notice the appended date param which helps skip browser caching.
fetch('https://static-global-s-msn-com.akamaized.net/hp-neu/sc/2b/a5ea21.ico?d='+Date.now())
.then(response => {
// Check if the response is successful
if (!response.ok)
throw new Error('Network response was not ok');
// At this point we can safely say the user has connection to the internet
console.log("Internet available");
})
.catch(error => {
// The resource could not be reached
console.log("No Internet connection", error);
});
So, Finally for my personal project i went with the 2nd option which involves requesting own server resource because basically there are many factors to tell if there is "Internet Connection" on a user's device, not just from your website container alone nor from a limited browser api.
Remember your users can also be in an environment where some websites or resources are blocked, prohibited and not accessible which in turn affects the logic of connectivity check. The best bet will be:
Try to access a resource on your own server because this is your users environment (Typically i use website's favicon because the response is very light and it is not frequently updated).
If there is no connection to the resource, simply say "Error in connection" or "Connection lost" when you need to notify the user rather than assume a broad "No internet connection" which depends on many factors.
I think it is a very simple way.
var x = confirm("Are you sure you want to submit?");
if (x) {
if (navigator.onLine == true) {
return true;
}
alert('Internet connection is lost');
return false;
}
return false;
The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.
Here is my code:
var xhr = new XMLHttpRequest();
//index.php is in my web
xhr.open('HEAD', 'index.php', true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
//If you use a cache storage manager (service worker), it is likely that the
//index.php file will be available even without internet, so do the following validation
if (xhr.status >= 200 && xhr.status < 304) {
console.log('On line!');
} else {
console.log('Offline :(');
}
}
}
I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.
I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.
$.ajax({
url: 'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
dataType: 'jsonp',
timeout: 5000,
error: function(xhr) {
if (xhr.status == 404) {
//internet connection working
}
else {
//internet is down (xhr.status == 0)
}
}
});
How about sending an opaque http request to google.com with no-cors?
fetch('https://google.com', {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors',
}).then((result) => {
console.log(result)
}).catch(e => {
console.error(e)
})
The reason for setting no-cors is that I was receiving cors errors even when disbaling the network connection on my pc. So I was getting cors blocked with or without an internet connection. Adding the no-cors makes the request opaque which apperantly seems to bypass cors and allows me to just simply check if I can connect to Google.
FYI: Im using fetch here for making the http request.
https://www.npmjs.com/package/fetch
My way.
<!-- the file named "tt.jpg" should exist in the same directory -->
<script>
function testConnection(callBack)
{
document.getElementsByTagName('body')[0].innerHTML +=
'<img id="testImage" style="display: none;" ' +
'src="tt.jpg?' + Math.random() + '" ' +
'onerror="testConnectionCallback(false);" ' +
'onload="testConnectionCallback(true);">';
testConnectionCallback = function(result){
callBack(result);
var element = document.getElementById('testImage');
element.parentNode.removeChild(element);
}
}
</script>
<!-- usage example -->
<script>
function myCallBack(result)
{
alert(result);
}
</script>
<a href=# onclick=testConnection(myCallBack);>Am I online?</a>
Just use navigator.onLine if this is true then you're online else offline
request head in request error
$.ajax({
url: /your_url,
type: "POST or GET",
data: your_data,
success: function(result){
//do stuff
},
error: function(xhr, status, error) {
//detect if user is online and avoid the use of async
$.ajax({
type: "HEAD",
url: document.location.pathname,
error: function() {
//user is offline, do stuff
console.log("you are offline");
}
});
}
});
You can try this will return true if network connected
function isInternetConnected(){return navigator.onLine;}
Here is a snippet of a helper utility I have. This is namespaced javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
You should use this with method detection else fire off an 'alternative' way of doing this. The time is fast approaching when this will be all that is needed. The other methods are hacks.
There are 2 answers forthis for two different senarios:-
If you are using JavaScript on a website(i.e; or any front-end part)
The simplest way to do it is:
<h2>The Navigator Object</h2>
<p>The onLine property returns true if the browser is online:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
</script>
But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.
The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

Categories

Resources