Skip to content

Instantly share code, notes, and snippets.

@igordata
Created June 10, 2015 21:42
Show Gist options
  • Save igordata/ad02bdeb84ba57bf9815 to your computer and use it in GitHub Desktop.
Save igordata/ad02bdeb84ba57bf9815 to your computer and use it in GitHub Desktop.
Standartified AJAX reply
const JSONResponse_STATUS_OK = 'OK', JSONResponse_STATUS_ERROR = 'ERROR';
/**
* JSONResponseParse
* @param text Unparsed text of server response
* @constructor
*/
function JSONResponseParse(text) {
try {
if (typeof text !== 'string') {
throw 'JSONResponse: Can\'t parse - not a string';
}
if (text.length < 28) {
throw 'JSONResponse: Can\'t parse - too short';
}
if (text.substr(0, 27) !== 'while(1){/*JSONResponse*/}[') {
throw 'JSONResponse: Can\'t parse - not a valid JSONResponse';
}
text = text.substr(27, text.length - 28);
return new JSONResponse(text);
}
catch (err) {
console.log(err);
}
return false;
}
function JSONResponse(text) {
/*
Used only for autocomplete in IDE
*/
this.status = 'OK';
this.messages = [{text: '', type: '', label: ''}];
this.data = [];
this.redirect = {url: '', delay: 0};
/**
* Draws a single message. To draw all messages use drawAllMessages().
* @param message array with message params
*/
this.drawMessage = function (message) {
};
this.drawAllMessages = function () {
};
var r = JSON.parse(text);
r.drawMessage = function (message) {
var r = '<div class="alert alert-' + message.type + '" role="alert">';
if (message.label) {
r += '<strong>' + message.label + '</strong> ';
}
r += message.text;
r += '</div>';
$('#ui-messages').append($(r));
};
r.drawAllMessages = function () {
$.each(r.messages, function (k, v) {
r.drawMessage(v);
})
};
r.popupFirstMessage = function () {
if (typeof r.messages[0] === 'undefined') {
return false;
}
var bootsrap2swal = {
danger: 'error',
warning: 'warning',
success: 'success',
info: 'info'
};
swal(r.messages[0].label, r.messages[0].text, bootsrap2swal[r.messages[0].type]);
};
r.checkRedirect = function () {
if (typeof r.redirect === 'undefined') {
return false;
}
;
if (typeof r.redirect.url === 'undefined') {
return false;
}
;
if (r.redirect.url) {
return true;
}
return false;
}
r.doRedirect = function () {
if (r.checkRedirect()) {
if (typeof r.redirect.delay === 'undefined') {
r.redirect.delay = 0;
}
setTimeout(function () {
window.location.href = r.redirect.url;
}, r.redirect.delay);
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment