Skip to content

Instantly share code, notes, and snippets.

@RafaelC457ro
Forked from EtienneR/user.js
Last active July 21, 2020 15:30
Show Gist options
  • Save RafaelC457ro/e10559848a8bebd9e0260d357abed12b to your computer and use it in GitHub Desktop.
Save RafaelC457ro/e10559848a8bebd9e0260d357abed12b to your computer and use it in GitHub Desktop.
XMLHttpRequest RESTful (GET, POST, PUT, DELETE)
// Get all users
var url = 'https://reqres.in/api/users';
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == '200') {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Get a user
var url = 'https://reqres.in/api/users/1';
var xhr = new XMLHttpRequest()
xhr.open('GET', url , true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == '200') {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Post a user
var url = 'https://reqres.in/api/users';
var data = {
"name": "morpheus",
"job": "leader"
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Update a user
var url = 'https://reqres.in/api/users/1';
var data = {
name: "neo",
job: "hero"
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Delete a user
var url = 'https://reqres.in/api/users/1';
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url, true);
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment