[[oktatas:web:jquery:ajax|< AJAX]]
====== jQuery - REST API elérése ======
* **Szerző:** Sallai András
* Copyright (c) Sallai András, 2022
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== 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:
* https://github.com/andteki/empjq
===== Végpontok =====
Egy REST API-ra van szükségünk, az alábbi végpontokkal.
Ennek elkészítését lásd [[oktatas:web:back-end_framework:laravel:laravel_api|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 ====
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');
});
}
Document
===== Dolgozók kezelése =====
==== Dolgozók kezelése JavaScript ====
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 = $('
');
$(' | ').text(value.id).appendTo(tr);
$(' | ').text(value.name).appendTo(tr);
$(' | ').text(value.city).appendTo(tr);
$(' | ').text(value.salary).appendTo(tr);
let tdDel = $(' | ').appendTo(tr);
let delButton = $('').appendTo(tdDel);
delButton.on('click', () => delEmployee(value.id));
delButton.attr('class', 'btn btn-warning')
let tdEdit = $(' | ').appendTo(tr);
let updateButton = $('').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 ====
Document