Tartalomjegyzék

< AJAX

jQuery - REST API elérése

Bevezetés

Az emp nevű REST API elérése jQuery segítségével, Bootstrap keretrendszerrel stílizálva.

A teljes megoldás a GitHub szerveren:

Végpontok

Egy REST API-ra van szükségünk, az alábbi végpontokkal. Ennek elkészítését lásd Laravel API leírásban

Végpont Metódus Auth CRUD Leírás
/employees GET nem read összes dolgozó
/employees POST igen create új dolgozó
/employees/{id} GET nem read egy dolgozó
/employees/{id} PUT igen update dolgozó frissítése
/employees/{id} DELETE igen delete dolgozó törlése
/register POST nem n/a regisztráció
/login POST nem n/a belépés
/logout POST nem n/a kilépés

Azonosítás

Belépés

src/auth.js
const host = 'http://localhost:8000/api/';
 
$('#loginButton').on('click', event => {
    login();
});
 
var login = () => {
    let endpoint = 'login';
    let url = host + endpoint;
    let authData = {
        name: $('#user').val(),
        password: $('#pass').val()
    }
    $.ajax({
        method: 'post',
        url: url,
        data: authData,
        dataType: 'json',
        success: (res) => {
            let authData = {
                name: res.name,
                token: res.token
            }
            localStorage.setItem('authData', JSON.stringify(authData));
        },
        error: () => {
            console.log('Hiba! A belépés sikertelen!')
        }
    });
}
 
 
$('#logoutButton').on('click', () => {
    logout();
});
 
function logout() {
    let endpoint = 'logout';
    let url = host + endpoint;
    let authDataJson = localStorage.getItem('authData');
    let authData = JSON.parse(authDataJson);
    let token = authData.token;
    let name = authData.name;
 
    let loginData = {
        name: name,
        tokenId: token
    }    
    console.log(loginData)
    $.ajax({
        type: 'post',
        url: url,
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        data: loginData
    })
    .done((res) => {
        console.log(res);
        localStorage.removeItem('authData');
        alert('Kilépve');
    });    
}
src/auth.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Dolgozók</h1>
        <nav class="nav m-3">
            <ul class="nav">
                <li class="nav-item">
                  <a class="nav-link" href="index.html">Dolgozók</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="auth.html">Azonosítás</a>
                </li>
            </ul>
            <button id="logoutButton"
            class="btn btn-primary">Kilépés</button>
        </nav>
 
 
        <div id="loginPanel"></div>
                <div class="mb-3">
                    <label for="user" class="form-label">Felhasználónév</label>
                    <input type="text" class="form-control" id="user"
                    value="janos">
                </div>
 
                <div class="mb-3">
                    <label for="pass" class="form-label">Jelszó</label>
                    <input type="password" class="form-control" id="pass"
                    value="titok">
                </div>
 
                <button type="button" class="btn btn-primary"
                id="loginButton">Belépés</button>
 
        </div>
 
    </div>
 
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="auth.js"></script>
 
</body>
</html>

Dolgozók kezelése

Dolgozók kezelése JavaScript

index.js
const addPanel = document.querySelector('#addPanel');
const delButton = document.querySelector('#delButton');
const editSaveButton = document.querySelector('#editSaveButton');
const editCancelButton = document.querySelector('#editCancelButton');
const newCancelButton = document.querySelector('#newCancelButton');
const host = 'http://localhost:8000/api/';
 
 
var getEmployees = () => {
    let endpoint = 'employees';
    let url = host + endpoint;
    $.ajax({
        url: url
    })
    .done((res) => {
        console.log(res);
        renderEmployees(res);
    });
}
 
var renderEmployees = (employees) => {
    $('#employeeTableBody').text('');
    $.each(employees, (index, value) => {
        let tr = $('<tr></tr>');
        $('<td></td>').text(value.id).appendTo(tr);
        $('<td></td>').text(value.name).appendTo(tr);
        $('<td></td>').text(value.city).appendTo(tr);
        $('<td></td>').text(value.salary).appendTo(tr);
 
        let tdDel =  $('<td></td>').appendTo(tr);
        let delButton = $('<button><i class="bi bi-trash"></i></button>').appendTo(tdDel);
        delButton.on('click', () => delEmployee(value.id));
        delButton.attr('class', 'btn btn-warning')
 
        let tdEdit = $('<td></td>').appendTo(tr);
        let updateButton = $('<button><i class="bi bi-pencil"></i></button>').appendTo(tdEdit);
        updateButton.on('click', () => editEmployee(value));
        updateButton.attr('type', 'button');
        updateButton.attr('class', 'btn btn-info');
        updateButton.attr('data-bs-toggle', 'modal');
        updateButton.attr('data-bs-target', '#editModal');
 
        $('#employeeTableBody').append(tr);
    });
}
 
 
$('#newSaveButton').on('click', () => {
    saveNewPanel();
});
 
var saveNewPanel = () => {
    let employee = {
        name: $('#newName').val(),
        city: $('#newCity').val(),
        salary: $('#newSalary').val()
    } 
    $('#newName').val('');
    $('#newCity').val('');
    $('#newSalary').val('');
    addEmployee(employee);
};
 
var addEmployee = (employee) => {
    let endpoint = 'employees';
    let url = host + endpoint;
    let authDataJson = localStorage.getItem('authData');
 
    if (authDataJson === null) {
        alert('Nem vagy bejelentkezve!')
        return;
    }    
 
    let authData = JSON.parse(authDataJson);
    let token = authData.token;
 
    $.ajax({
        type: 'post',
        url: url,
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        data: employee
    })
    .done((res) => {
        console.log(res);
        getEmployees();
    });
};
 
var delEmployee = (id) => {
    deleteEmployee(id);
};
 
var deleteEmployee = (id) => {
    let endpoint = 'employees' + '/' + id;
    let url = host + endpoint;
    let authDataJson = localStorage.getItem('authData');
 
    if (authDataJson === null) {
        alert('Nem vagy bejelentkezve!')
        return;
    }    
 
    let authData = JSON.parse(authDataJson);
    let token = authData.token;
 
    $.ajax({
        type: 'delete',
        url: url,
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`
        },
    })
    .done((res) => {
        console.log(res);
        getEmployees();
    });
};
 
var editEmployee = (employee) => {
    $('#editPanel').fadeIn(400);
    $('#editedId').val(employee.id);
    $('#editedName').val(employee.name);
    $('#editedCity').val(employee.city);
    $('#editedSalary').val(employee.salary);
}
 
$('#editSaveButton').on('click', () => {
    let employee = {     
        id: $('#editedId').val(),   
        name: $('#editedName').val(),
        city: $('#editedCity').val(),
        salary: $('#editedSalary').val()
    }
    updateEmployee(employee);
    $('#editPanel').fadeOut(400);
});
 
var updateEmployee = (employee) => {
    let endpoint = 'employees' + '/' + employee.id;
    let url = host + endpoint;
    let authDataJson = localStorage.getItem('authData');
 
    if (authDataJson === null) {
        alert('Nem vagy bejelentkezve!')
        return;
    }
 
    let authData = JSON.parse(authDataJson);
    let token = authData.token;
 
    $.ajax({
        type: 'put',
        url: url,
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        data: employee
    })
    .done((res) => {
        console.log(res);
        getEmployees();
    });
}
 
getEmployees();

Dolgozók kezelése HTML

src/index.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="font/bootstrap-icons.css">
</head>
<body>
    <div class="container">
        <h1>Dolgozók</h1>
        <nav class="m-3">
            <ul class="nav">
                <li class="nav-item">
                  <a class="nav-link" href="index.html">Dolgozók</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="auth.html">Azonosítás</a>
                </li>
            </ul>            
 
        </nav>
 
        <!-- Button trigger modal -->
        <button type="button" class="btn btn-primary" 
        data-bs-toggle="modal" data-bs-target="#addModal">
            Hozzáadás
        </button>
 
 
        <table id="employeeTable" class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Név</th>
                    <th>Település</th>
                    <th>Fizetés</th>
                </tr>                
            </thead>
            <tbody id="employeeTableBody">
 
            </tbody>
        </table>
    </div>
 
 
  <!-- add Modal -->
  <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Hozzáadás</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
 
            <div id="addPanel">
                <div class="mb-3">
                    <label for="newName" class="form-label">Név</label>
                    <input type="text" id="newName"
                    class="form-control">
                </div>
                <div class="mb-3">
                    <label for="newCity" class="form-label">Település</label>
                    <input type="text" id="newCity"
                    class="form-control">
                </div>
                <div class="mb-3">
                    <label for="newSalary" class="form-label">Fizetés</label>
                    <input type="text" id="newSalary"
                    class="form-control">
                </div>
            </div>
 
 
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" 
          data-bs-dismiss="modal">Bezárás</button>
          <button type="button" class="btn btn-primary"
          id="newSaveButton"
          data-bs-dismiss="modal">Mentés</button>
        </div>
      </div>
    </div>
  </div>    
 
 
  <!-- edit Modal -->
  <div class="modal fade" id="editModal" 
  tabindex="-1" aria-labelledby="exampleModalLabel" 
  aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Dolgozó szerkesztése</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
 
            <div id="editPanel">
                <div class="mb-3">
                    <label for="editedId" 
                    class="form-label">Id</label>
                    <input type="text" id="editedId"
                    class="form-control" readonly>
                </div>
                <div class="mb-3>
                    <label for="editedName" 
                    class="form-label">Név</label>
                    <input type="text" id="editedName"
                    class="form-control">
                </div>
                <div class="mb-3>
                    <label for="editedCity"
                    class="form-label">Település</label>
                    <input type="text" id="editedCity"
                    class="form-control">
                </div>
                <div>
                    <label for="editedSalary">Fizetés</label>
                    <input type="text" id="editedSalary"
                    class="form-control">
                </div>
 
            </div>
 
 
 
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" 
          data-bs-dismiss="modal">Bezárás</button>
          <button type="button" class="btn btn-primary"
          data-bs-dismiss="modal"
          id="editSaveButton">Mentés</button>
        </div>
      </div>
    </div>
  </div>            
 
 
 
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="js/bootstrap.js"></script>
    <script src="index.js"></script>
 
</body>
</html>