Skip to content

Instantly share code, notes, and snippets.

@PixieStudio
Forked from EtienneR/user.js
Created June 10, 2020 23:05
Show Gist options
  • Select an option

  • Save PixieStudio/c3d169a6dc29f4738bc018c83b305641 to your computer and use it in GitHub Desktop.

Select an option

Save PixieStudio/c3d169a6dc29f4738bc018c83b305641 to your computer and use it in GitHub Desktop.

Revisions

  1. @EtienneR EtienneR created this gist Jan 7, 2016.
    87 changes: 87 additions & 0 deletions user.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    // 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);