Last active
August 30, 2016 11:23
-
-
Save kottenator/10464598 to your computer and use it in GitHub Desktop.
Setup jQuery AJAX & show errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Setup jQuery AJAX | |
* | |
* Requires noty.js and 2 its layouts: noty/layouts/top.js, noty/layouts/topRight.js | |
*/ | |
$.ajaxSetup({ | |
error: function(xhr, status, error) { | |
// we ignore aborted XHR or when user press F5 while XHR is in progress | |
if (status == 'abort' || xhr.readyState == 0) | |
return; | |
// default error message | |
var text = 'Sorry, but request has failed'; | |
if (error) | |
text += ' (' + error + ')'; | |
if (xhr.responseText) { | |
text = xhr.responseText; | |
if (text.toLowerCase().indexOf('</html>') != -1) { | |
// HTML error message will be displayed in <iframe> | |
var msg = noty({type: 'error', layout: 'top'}); | |
var iframe = $('<iframe>').appendTo(msg.$message.find('.noty_text')); | |
var doc = iframe.contents()[0]; | |
doc.open(); | |
doc.write(text); | |
doc.close(); | |
var width = msg.$message.width(); | |
iframe.width(width); | |
var height = Math.min($(doc).find('body').outerHeight(true), $(document).height()); | |
iframe.height(height); | |
} else if (text.length > 2000) { | |
// large error message > 2000 symbols | |
noty({type: 'error', layout: 'top', text: text}); | |
} else { | |
noty({type: 'error', layout: 'topRight', text: text}); | |
} | |
} else { | |
noty({type: 'error', layout: 'topRight', text: text}); | |
} | |
}, | |
/** | |
* Handles error and info messages from backend. Example JSON: | |
* | |
* {data: 'message', type: 'error', text: 'An error has occurred'} | |
*/ | |
success: function(response, status, xhr) { | |
if (response && response.data == 'message') { | |
noty({ | |
'type': response.type, | |
'text': response.text | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment