Snippets
Created by
Oleg Antonyan
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | (function () {
setInterval(function () {
var xmlhttp = new XMLHttpRequest();
var url = '/api/state';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var data = JSON.parse(xmlhttp.responseText);
process_ok(data)
} catch(err) {
console.log(err)
process_error(xmlhttp.responseText + "<br />" + err);
}
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}, 1000);
function set_element_inner_html(element_id, text) {
document.getElementById(element_id).innerHTML = text;
}
function add_element_class(element_id, klass) {
document.getElementById(element_id).classList.add(klass)
}
function remove_element_class(element_id, klass) {
document.getElementById(element_id).classList.remove(klass)
}
function show_element(id) {
remove_element_class(id, "hidden");
}
function hide_element(id) {
add_element_class(id, "hidden");
}
function process_ok(data) {
console.log(data);
clear_error()
switch(data.template) {
case 'items':
display_items_with_grand_total(data);
break;
case 'finalize':
display_thanks(data);
break;
case 'empty':
clear_all();
break;
}
};
function process_error(data) {
console.log(data);
display_error(data);
};
function display_error(text) {
set_element_inner_html('error-message', text)
}
function clear_error() {
display_error('');
}
function clear_all() {
clear_error();
hide_element("grand-total-block");
hide_element("items-block");
hide_element("thanks-block");
}
function display_items_with_grand_total(data) {
hide_element("thanks-block");
show_element("grand-total-block");
show_element("items-block");
set_element_inner_html('grand-total-sum-value', data.total.amount);
set_element_inner_html('grand-total-got-value', data.total.got);
set_element_inner_html('grand-total-change-value', data.total.change);
var item_template = "<li>{{name}} - {{price}}, {{qty}} на {{subtotal}}</li>";
var html = "";
for(var i = 0; i < data.items.length; i++) {
item = data.items[i];
html += item_template.replace("{{name}}", item.name)
.replace("{{price}}", item.price)
.replace("{{qty}}", item.quantity)
.replace("{{subtotal}}", item.subtotal);
}
set_element_inner_html("items-list", html);
scroll_items_bottom();
}
function display_thanks(data) {
hide_element("grand-total-block");
hide_element("items-block");
show_element("thanks-block");
set_element_inner_html("thanks-text", data.text);
}
function scroll_items_bottom() {
var element = document.getElementById("items-block");
element.scrollTop = element.scrollHeight;
}
window.onload = clear_all;
})();
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.