Skip to content

Instantly share code, notes, and snippets.

@MuriloMazzeu
Last active October 8, 2017 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MuriloMazzeu/dfa183f405173731ae49808bdbddcf82 to your computer and use it in GitHub Desktop.
Save MuriloMazzeu/dfa183f405173731ae49808bdbddcf82 to your computer and use it in GitHub Desktop.
Javascript's Snippets
const $ajax = (url, data) => new function() {
this.success
this.error
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = e => {
if (xhr.readyState == 4) {
if(xhr.status == 200) this.success(xhr.responseText);
else this.error(xhr.status);
}
}
this.get = (s, e) => {
if(s) this.success = s;
if(e) this.error = e;
xhr.open('GET', url + '?data=' + JSON.stringify(data), true);
xhr.send()
}
this.put = (s, e) => {
if(s) this.success = s;
if(e) this.error = e;
xhr.open('PUT', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-HTTP-Method-Override', 'PUT');
xhr.send(JSON.stringify(data))
}
this.post = (s, e) => {
if(s) this.success = s;
if(e) this.error = e;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(JSON.stringify(data))
}
this.delete = (s, e) => {
if(s) this.success = s;
if(e) this.error = e;
xhr.open('DELETE', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE');
xhr.send(JSON.stringify(data));
}
}
//ONLY FOR DEVELOPMENT ENVIRONMENT
const sleep = milliseconds => {
const now = new Date().getTime();
while(new Date().getTime() < now + milliseconds);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment