Check Avaibility of a page before loading using jquery/ajax
Posted
by
overcomer
on Stack Overflow
See other posts from Stack Overflow
or by overcomer
Published on 2012-10-26T10:15:23Z
Indexed on
2012/10/29
11:01 UTC
Read the original article
Hit count: 143
Is it possible check the Accessibility of a page before loading it?
I have a form, running on mobile device using wireless connection. The problem is: not always this connection is avaible and i would like to alert the user when is doing a submit or an unload of the page.
The problem is that the page contains elements doing redirect like this:
<input type="button" value="MyText" onClick="script1;script2;...window.location='mylocation" />
If the user click on this button and the server is not achievable, i will recive some undesiderable errors.
Also if I want to generalize my script i do not know the value of "mylocation" previously.
The page contains elements to submit the Form also:
<input type="submit" name="SUBMIT" value="MyValue" onClick="return eval('validationForm()')" />
For the submitting I'm using the ajaxForm plugin and it works quite well. This is a snippet of code:
Thanks to your answer I found the solution to the problem. That's the code:
function checkConnection(u,s){
$.ajax({
url:u,
cache:false,
timeout:3000,
error: function(jqXHR, textStatus)
{
alert("Request failed: " + textStatus );
},
success: function()
{
eval(s);
}
});
}
$(document).ready(function() {
// part of the function that checks buttons with redirect
// for any input that contain a redirect on onClick attribute ("window.locarion=")
$("input[type=button]").each(function(){
var script = $(this).attr("onClick");
var url = "";
var position = script.indexOf("window.location") ;
if (position >= 0) { // case of redirect
url = script.substring(position+17, script.lenght);
url = url.split("\'")[0];
url = "\'"+url+"\'"; // that's my url
script = "\""+script+"\""; // that's the complete script
$(this).attr("onClick","checkConnection("+url+","+script+")");
}
});
// part of the function that checks the submit buttons (using ajaxForm plugin)
var is_error = false;
var options = {
error: function() {
if (alert("Error Message")==true) {
}
is_error = true;
},
target: window.document,
replaceTarget: is_error,
timeout: 3000
};
$("#myForm").ajaxForm(options);
});
I hope that this will be usefull.
© Stack Overflow or respective owner