/** * Created by vitaliiomelchuk on 03.04.17. */ if (navigator.userAgent.match(/(iPad|iPhone|iPod|Android|Silk)/gi)) { document.title = "Інтернет-магазин цінних книг - Mediason"; document.querySelector('meta[name="description"]').setAttribute("content", "Твори відомих авторів та професіоналів"); } function updateCartView(count_selector, price_selector, response_json) { if (Object.prototype.hasOwnProperty.call(response_json, 'total_items_count')) { var cartCountElement = document.querySelectorAll(count_selector); if (cartCountElement) { if (cartCountElement.hasOwnProperty('innerHTML')) { cartCountElement.innerHTML = response_json.total_items_count; } else { for (var i in cartCountElement) { cartCountElement[i].innerHTML = response_json.total_items_count; } } } } if (Object.prototype.hasOwnProperty.call(response_json, 'total_items_price')) { var cartPriceElement = document.querySelectorAll(price_selector); if (cartPriceElement) { if (cartPriceElement.hasOwnProperty('innerHTML')) { cartPriceElement.innerHTML = response_json.total_items_price; } else { for (var i in cartPriceElement) { cartPriceElement[i].innerHTML = response_json.total_items_price; } } } } } function checkCart(count_selector, price_selector) { var xhr = new XMLHttpRequest(); xhr.open('GET', '/eshop/add_to_cart/'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function () { if (xhr.status === 200) { var resp = JSON.parse(xhr.responseText); window.console.log(resp); updateCartView(count_selector, price_selector, resp); } else { alert('Request failed. Returned status of ' + xhr.status); } }; xhr.send(); } function addToCart(article_id, count, count_selector, price_selector) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/eshop/add_to_cart/'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function () { if (xhr.status === 200) { var resp = JSON.parse(xhr.responseText); window.console.log(resp); updateCartView(count_selector, price_selector, resp); } else { alert('Request failed. Returned status of ' + xhr.status); } }; xhr.send(JSON.stringify({'article_id': article_id, 'count': count})) } function removeFromCart(item_id, count_selector, price_selector) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/eshop/remove_from_cart/'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function () { if (xhr.status === 200) { var resp = JSON.parse(xhr.responseText); updateCartView(count_selector, price_selector, resp); } else { alert('Request failed. Returned status of ' + xhr.status); } }; xhr.send(JSON.stringify({'item_id': item_id})) } function initCart(count_selector, price_selector) { window.addEventListener('DOMContentLoaded', checkCart(count_selector, price_selector)); }