Skip to content

Instantly share code, notes, and snippets.

@blentz100
Last active April 29, 2022 15:20
Show Gist options
  • Save blentz100/3734b2141479311f74f83ecb83770600 to your computer and use it in GitHub Desktop.
Save blentz100/3734b2141479311f74f83ecb83770600 to your computer and use it in GitHub Desktop.
Ajax example for crudcrud.com
class House {
constructor(name) {
this.name = name;
this.rooms = [];
}
addRoom(name, area) {
this.rooms.push(new Room(name, area));
}
}
class Room {
constructor(name, area) {
this.name = name;
this.area = area;
}
}
class HouseService {
static houses = [];
// get new crud crud code every 24 hours
static url = "https://crudcrud.com/api/5382209a76bc4c989c49dddfc7959002/house";
static getAllHouses() {
console.log("called getAllHouses")
const data = $.get(this.url);
return data;
}
static getHouse(id) {
return $.get(`${this.url}/${id}`);
}
static createHouse(house) {
return $.ajax({
url: this.url,
data: JSON.stringify(house),
dataType: "json",
type: "POST",
contentType: "application/json",
crossDomain: true,
});
}
static updateHouse(house) {
const id = house._id;
delete house._id;
return $.ajax({
url: `${this.url}/${id}`,
data: JSON.stringify(house),
contentType: "application/json",
crossDomain: true,
type: "PUT",
})
}
static deleteHouse(id) {
return $.ajax({
url: `${this.url}/${id}`,
type: "DELETE"
})
}
}
class DOMManager {
static houses;
static getAllHouses() {
HouseService.getAllHouses()
.then(houses => this.render(houses));
}
static createHouse(name) {
HouseService.createHouse(new House(name))
.then(() => HouseService.getAllHouses())
.then((houses) => { this.render(houses);})
}
static deleteHouse(id) {
HouseService.deleteHouse(id)
.then(() => HouseService.getAllHouses())
.then((houses) => { this.render(houses);});
}
static addRoom(id) {
console.log("called addroom");
let matchingHouse = {};
// get copy of hosue needing update
for (let house of this.houses) {
if (house._id == id) {
matchingHouse = Object.assign({}, house);
break;
}
}
// add new room to copy of house needing update
matchingHouse.rooms.push(new Room($(`#${id}-room-name`).val(), $(`#${id}-room-area`).val()));
// call updateHosue service with new hosue object
HouseService.updateHouse(matchingHouse)
.then(() => DOMManager.getAllHouses());
}
static deleteRoom(houseId, roomName) {
for(let house of this.houses) {
if (house._id == houseId) {
console.log("found house")
for(let room of house.rooms) {
if(room.name == roomName) {
house.rooms.splice(house.rooms.indexOf(room), 1);
console.log("found room")
HouseService.updateHouse(house)
.then(() => DOMManager.getAllHouses());
}
}
}
}
}
static render(houses) {
console.log("rendering hosues")
console.log(houses)
this.houses = houses;
$('#app').empty();
for(let house of houses) {
$('#app').prepend(
`<div id="${house._id}" class="card">
<div class="card-header">
<h2>${house.name}</h2>
<button class="btn btn-danger" onclick="DOMManager.deleteHouse('${house._id}')">Delete</button>
</div>
<div class="card-body">
<div class="card">
<div class="row">
<div class="col-sm">
<input type="text" id="${house._id}-room-name" class="form-control" placeholder="Room Name">
</div>
<div class="col-sm">
<input type="text" id="${house._id}-room-area" class="form-control" placeholder="Room Area">
</div>
<button id="${house._id}-new-room" onclick="DOMManager.addRoom('${house._id}')" class="btn btn-primary form-control">Add Room</button>
</div>
</div>
</div>
</div>`
);
for(let room of house.rooms) {
$(`#${house._id}`).find('.card-body').append(
`<p>
<span id="name-${room._id}"><strong>Name: </strong>${room.name}</span>
<span id="area-${room._id}"><strong>Area: </strong>${room.area}</span>
<button class="btn btn-danger" onclick="DOMManager.deleteRoom('${house._id}', '${room.name}')">Delete Room</button>
</p>`
)
}
}
}
}
$('#create-new-house').click(() => {
DOMManager.createHouse($('#new-house-name').val());
$('#new-house-name').val = "";
})
DOMManager.getAllHouses();
/* From Joey Wilson
5:58
There's the updated code.
5:59
For update, the "dataType" property had to be removed.
It was causing jquery/ajax to expect a json response body, but the api does not return anything for put requests, so jquery was throwing calling the "error" callback instead of the "then" callback.
5:59
For the delete room part I was using "id", but the room objects do not have an "_id" property.
5:59
So we changed it to "name", which the room object does have, and it works now.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment