Lecture 8 Revision

RESTful API’s and JavaScript

JavaScript Object Notation (JSON)

represent an object

JSON can be nested

alt text

RESTFul API’s

How are API’s used in Web Development?

What is a RESTful API?

Stateless Communication

Resource-Based

HTTP Methods

CRUD with RESTful

Javascript recap

Building Block JavaScript Example
Variable Assignment const y = 2; //Declare a constact
let x = 5; // Block scoped variable that can be changed
String let myString = "Hello, world!";
Integer let myInt = 10;
Float let myFloat = 20.5;
Boolean let myBool = true;
Array/List let myList = [1, 2, 3, 4, 5];
Object let myObject = {'key1': 'value1', 'key2': 'value2’};
Conditional (if) if (x > 5) { console.log("x is greater than 5"); }
Conditional (if-else) if (x > 5) { console.log("x is greater than 5"); }
else { console.log("x is less than or equal to 5"); }
Conditional (if-else if-else) if (x > 5) { console.log("x is greater than 5"); }
else if (x == 5) { console.log("x is equal to 5"); }
else { console.log("x is less than 5"); }
Functions function myFunction() { console.log("This is a function"); }
let square = x => x * x;
let add = (a, b) => a + b;
let getObject = () => ({ name: "John", age: 30 });
console.log(getObject()); // Output: { name: "John", age: 30 }
function createGreeting(name) {
return Hello, my name is ${name}.;
}
const greeting = createGreeting("Alice");
console.log(greeting);

Adding a list (example 1)

Code Page
alt text alt text

How it works:

HTML Structure: The page includes a button labeled "Add New Item" and an unordered list (<ul>) with an initial list item.

JavaScript Logic: When the button is clicked, the JavaScript code executes:

Adding a list (example 2)

Code Page
alt text alt text

How This Works:

HTML Structure: The page includes a button and a table with headers. Below the table, there's a <template> tag containing a template for the table rows.

Template Tag : Inside the <template> tag, there’s a predefined table row (<tr>) with two cells (<td>). This row will not be displayed on the page until it is instantiated by JavaScript.

Fetch API

fetch('<?= base_url("item"); ?>/')
    .then(response => response.json())
    .then(items => {
        items.forEach(item => {
            const li = createListItem(item);
            todoList.appendChild(li);
        });
    });

Two ways to handle

alt text

Todo List app

<template id="itemTemplate">
    <li class="list-group-item">
        <div class="form-check">
            <input class="form-check-input" type="checkbox">
            <label class="form-check-label"></label>
            <input type="text" class="form-control d-none">
        </div>
        <div class="btn-group btn-group-sm float-end">
            <button type="button" class="btn btn-secondary edit-btn">Edit</button>
            <button type="button" class="btn btn-danger delete-btn">Delete</button>
        </div>
    </li>
</template>
<script>
    const todoForm = document.getElementById('todoForm');
    const newItem = document.getElementById('newItem');
    const todoList = document.getElementById('todoList');
    const itemTemplate = document.getElementById('itemTemplate');

    // Fetch and render existing items
    fetch('<?= base_url("item"); ?>/')
        .then(response => response.json())
        .then(items => {
            items.forEach(item => {
                const li = createListItem(item);
                todoList.appendChild(li);
            });
        });
 

// Create list item from template
function createListItem(item) {
    const li = itemTemplate.content.firstElementChild.cloneNode(true);
    li.dataset.id = item.id;
    const checkbox = li.querySelector('.form-check-input');
    checkbox.checked = item.completed === '1'; // Check the checkbox if completed is '1'
    const label = li.querySelector('.form-check-label');
    label.textContent = item.item;
    return li;
}
</script>       
<script>
// Handle item editing
todoList.addEventListener('keypress', event => {
    if (event.key === 'Enter') {
        const li = event.target.closest('li');
        const label = li.querySelector('.form-check-label');
        const input = li.querySelector('input[type="text"]');
        const id = li.dataset.id;
        const item = input.value;

        fetch(`<?= base_url("item"); ?>/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ item })
        })
        .then(() => {
            label.textContent = item;
            label.classList.remove('d-none');
            input.classList.add('d-none');
        });
    }
});

// Handle item actions
todoList.addEventListener('click', event => {
    const li = event.target.closest('li');
    const checkbox = li.querySelector('.form-check-input');
    const label = li.querySelector('.form-check-label');
    const input = li.querySelector('input[type="text"]');
    const editBtn = li.querySelector('.edit-btn');
    const deleteBtn = li.querySelector('.delete-btn');
    const id = li.dataset.id;

    if (event.target === checkbox) {
        const completed = checkbox.checked;
        fetch(`<?= base_url("item"); ?>/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ completed })
        });
    } else if (event.target === editBtn) {
        label.classList.add('d-none');
        input.classList.remove('d-none');
        input.value = label.textContent;
        input.focus();
    } else if (event.target === deleteBtn) {
        fetch(`<?= base_url("item"); ?>/${id}`, { method: 'DELETE' })
            .then(() => li.remove());
    }
});
</script>