Skip to content

Instantly share code, notes, and snippets.

@alihesari
Forked from EtienneR/user.js
Created January 1, 2019 15:15
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 alihesari/23733f30143a79541667cb84fcd02e8a to your computer and use it in GitHub Desktop.
Save alihesari/23733f30143a79541667cb84fcd02e8a to your computer and use it in GitHub Desktop.
XMLHttpRequest RESTful (GET, POST, PUT, DELETE)
// Get all users
var url = "http://localhost:8080/api/v1/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 = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest()
xhr.open('GET', url+'/1', 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 = "http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John";
data.lastname = "Snow";
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 = "http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John2";
data.lastname = "Snow2";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url+'/12', 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 = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'/12', 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