Skip to content
Snippets Groups Projects
Commit 1bea63fb authored by Ernests Malnacs's avatar Ernests Malnacs
Browse files

Added creating trainers, through a form.

parent 6d97fb98
Branches create-trainer
No related tags found
No related merge requests found
......@@ -13,7 +13,7 @@ function updateDetails(trainerId) {
parent.innerHTML = `
<div class="card" id="${tr.id}_card">
<img src="${tr.profileUrl}" class="card-img-top" alt="${tr.name}">
${tr.profileUrl ? `<img src="${tr.profileUrl}" class="card-img-top" alt="${tr.name}">` : ''}
<div class="card-body">
<h5 class="card-title">${tr.name}</h5>
<p class="card-text">
......@@ -52,4 +52,45 @@ function createTrainersTable() {
</tbody>
</table>
`
}
function refreshTable() {
tableParentId = "tableDiv";
detailsParentId = "detailsDiv";
fetch('/pokemon/api/trainers')
.then(res => res.json())
.then(data => {
trainers = data;
createTrainersTable()
})
.catch(err => {
console.error(`Unable to fetch trainers: ${err.status}`);
console.error(err);
});
}
function handleTrainerCreate(event) {
event.preventDefault();
const trainerName = document.getElementById("trainerName").value;
const postData = JSON.stringify({name: trainerName})
fetch(
'api/trainers', {
method: 'POST',
headers: {
'Content-Type' : 'application/json'
},
body: postData
})
.then(response => response.json())
.then(data => {
refreshTable();
})
.catch(err => {
console.error('Error', err);
})
}
\ No newline at end of file
......@@ -15,30 +15,32 @@
<body>
<script src="js/trainers.js"></script>
<script>
tableParentId = "tableDiv";
detailsParentId = "detailsDiv";
fetch('/pokemon/api/trainers')
.then(res => res.json())
.then(data => {
trainers = data;
createTrainersTable()
})
.catch(err => {
console.error(`Unable to fetch trainers: ${err.status}`);
console.error(err);
});
</script>
<h1>Trainers</h1>
<div class="container">
<div class="row">
<div id="tableDiv" class="col-8">No data</div>
<div id="detailsDiv" class="col-4">No data</div>
<div style="padding:20px" >
<form id="createTrainerForm">
<div class="form-group">
<label for="trainerName">Trainer Name</label>
<input type="text" class="form-control" id="trainerName" placeholder="Enter Trainer Name">
</div>
<button type="submit" class="btn btn-primary">Create Trainer</button>
</form>
</div>
<div class="container">
<div class="row">
<div id="tableDiv" class="col-8">No data</div>
<div id="detailsDiv" class="col-4">No data</div>
</div>
</div>
</div>
<script>
const createTrainerForm = document.getElementById("createTrainerForm");
createTrainerForm.addEventListener("submit", handleTrainerCreate);
refreshTable();
</script>
</body>
</html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment