Showing an alert if an Ajax call fails

If our visitor's Internet connection fails, our script should tell them the Ajax will not work either.

How to do it...

Create a test script that makes an Ajax call. Ensure the call will fail by using a fake domain that will not resolve.

<form action="" method="get">
<input type="button" id="mybutton" value="Ajax!"/>
</form>
<script type="text/javascript">
var myJax = new Request({
url: 'http://incorrectdomain.com/nofileexists',
onFailure: function() {
alert('error connecting, Ajax call has failed :(');
},
onSuccess: function(response) {
alert('Success! Here is the response: '+response);
}
});
$('mybutton').addEvent('click', function ajax_it() {
myJax.send();
});
</script>

How it works...

Using a fake URL will ...

Get MooTools 1.3 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.