I am building a web application that needs to be working seamless when being online or off line. For this need to be able to check my connection with the server.
The main devices that are to be supported are iphone3+4, ipad, a netbook with chrome and android 2.1+.
The navigator.onLine
is not exactly what I am looking for. This is unreliable and only checks if you have connectivity, not if you are connected to a specific server.
I tried jQuery.getJSON
to connect to a ping web-service on my server. This works fine in chrome on the netbook but the native android browser returns null. Ipod touch doesn't do anything at all.
I could use some help with this..
I don't exactly understand your situation but it sounds like you should use ...
$.ajax({
url: "test.html",
cache: false,
async : false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
// some error code.
},
success: function(html){
// do something.
}
});
http://api.jquery.com/jQuery.ajax/
async : false is to "block" the request, using test.html or any other simple file (basically we're just trying to connect.) You could use the timeout to set some short time period.
Then see if you get get an error or success ...
error(XMLHttpRequest, textStatus, errorThrown)
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.This handler is not called for
JSONP requests, because they do not
use an XMLHttpRequest.
If there is an error, fire some function to handle that, if you get the file back you are good to go.
It after all had to do with the 'same origin policy' (see comments).
This was resolved by using JSONP.
The strange thing is that it looks like I am dealing with the same domain, but oke here the code...
CLIENT-SIDE:
jQuery.getJSON("url?callback=?", function(data) {
//Do something
});
SERVER-SIDE:
@RequestMapping(value="url", method=RequestMethod.GET)
public void ping(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String output = request.getParameter("callback") + "({0:1});";
response.setContentType("text/javascript");
response.getWriter().write(output);
}
I had a similar issue using $.getJSON
in a web app. It works well from many browsers except on Android. In fact, my app is supposed to work offline and then I use a manifest where the JSON file is declared as CACHE. For the initial load, it works well but for the next pages load the app is blocked when loading the JSON file.
I suspect that the offline cache is perceived as another origin than the initial server and the process is blocked.
Hope it helps