I’ve written a little ruby Sinatra app. From time to time an error is thrown (e.g. database connection is not there). However the default index page always works (no database connection necessary).
I’ve used jQuery to handle the request that triggers the creation of data. But when a backend error occurs, I’d like to show the default error page. This is not working because jQuery creates the request and just ignores the error (so nothing happens when the database is not available). My code looks something like this:
$(document).ready(function() {
$("form").bind("submit", function(event) {
event.preventDefault();
$.ajax({
type:"POST",
url:"/new",
data:$("#form").serialize(),
dataType:"json",
success:function(data){
// handling of input data
},
error:function(xhr, ajaxOptions, thrownError){
// show default error page
}
});
});
});
I managed to achieve what I wanted by doing this:
error:function(xhr, ajaxOptions, thrownError){
alert something;
}
But I suppose this just works because of the syntax error (The correct syntax would be alert(“something”);)
Is there a proper way to redirect to the default error page?
Look at the default ajax settings, so you don´t have to do this for each Ajax request you make. http://api.jquery.com/jQuery.ajaxSetup/
If you have an ajax request and your Database is not available, there is not Ajax error because the page can still be called. Maybe you have to check the response on the success page if it contains “ERROR” or something? Or change the header code to a different one then 200 so the error of the Ajax request will be called.