function request(url) { var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); return xhr; } function check(id) { var checkbox = document.getElementById("task-" + id); if (checkbox.checked) { var xhr = request("/v1/do"); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { data = JSON.parse(xhr.responseText); if (data.task) { $("#task-" + data.task.id).prop("checked", data.task.done); } else { console.log(data); // NOTE TEMPORARY (handle errors better!) } } } xhr.send(JSON.stringify({api_key: API_KEY, id: id})); } else { var xhr = request("/v1/undo"); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { data = JSON.parse(xhr.responseText); if (data.task) { $("#task-" + data.task.id).prop("checked", data.task.done); } else { console.log(data); // NOTE TEMPORARY (handle errors better!) } } } xhr.send(JSON.stringify({api_key: API_KEY, id: id})); } } function new_task() { var text = document.getElementById("new-task-input"); var xhr = request("/v1/new"); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { data = JSON.parse(xhr.responseText); if (data.task) { $("#new-task").before("
  • " + data.task.content + "
  • "); } else { console.log(data); // NOTE TEMPORARY (handle errors better!) } } } xhr.send(JSON.stringify({api_key: API_KEY, content: text.value})); return false; // prevent form submission } function new_api_key() { var xhr = request("/new-api-key"); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { data = JSON.parse(xhr.responseText); if (data.api_key) { $("#new-api-key").before("
  • " + data.api_key.key + "
  • "); } else { console.log(data); // NOTE TEMPORARY (handle errors better!) } } } xhr.send(); // NOTE may need to send empty string or empty JSON object }