Create generic request javascript method

master
Guillaume Dott 2015-10-30 12:58:02 +01:00
parent 728ea6b3ee
commit 510bf65dcd
1 changed files with 13 additions and 21 deletions

View File

@ -1,3 +1,13 @@
function request(method, url, data, loadevent) {
var req = new XMLHttpRequest();
req.open(method, url);
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.addEventListener('load', loadevent);
req.send(data)
}
function initButtons() { function initButtons() {
var buttons = document.querySelectorAll('button[data-action=remove-movie]'); var buttons = document.querySelectorAll('button[data-action=remove-movie]');
for (var i = 0; i < buttons.length; i++) { for (var i = 0; i < buttons.length; i++) {
@ -38,45 +48,27 @@ function search(value) {
var url = '/search?search=' + encodeURIComponent(value) var url = '/search?search=' + encodeURIComponent(value)
window.history.pushState({value: value}, "", url); window.history.pushState({value: value}, "", url);
var req = new XMLHttpRequest(); request('GET', url, null, function(e) {
req.open('GET', url);
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.addEventListener('load', function(e) {
document.getElementById('movies').parentNode.innerHTML = this.responseText; document.getElementById('movies').parentNode.innerHTML = this.responseText;
}); });
req.send()
} }
function removeMovie(id) { function removeMovie(id) {
var data = new FormData(); var data = new FormData();
data.append('id', id); data.append('id', id);
var req = new XMLHttpRequest(); request('POST', '/remove', data, function(e) {
req.open('POST', '/remove');
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.addEventListener('load', function(e) {
document.querySelector('.movie[data-id="' + id + '"]').parentNode.remove(); document.querySelector('.movie[data-id="' + id + '"]').parentNode.remove();
}); });
req.send(data)
} }
function viewMovie(id) { function viewMovie(id) {
var data = new FormData(); var data = new FormData();
data.append('id', id); data.append('id', id);
var req = new XMLHttpRequest(); request('POST', '/view', data, function(e) {
req.open('POST', '/view');
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.addEventListener('load', function(e) {
document.querySelector('.movie[data-id="' + id + '"] button[data-action="view-movie"]').parentNode.remove(); document.querySelector('.movie[data-id="' + id + '"] button[data-action="view-movie"]').parentNode.remove();
}); });
req.send(data)
} }
document.addEventListener('DOMContentLoaded', function(event) { document.addEventListener('DOMContentLoaded', function(event) {