Whenever I submit a post request containing JSON data to the server, the page gets refreshed after updating the username and score. Surprisingly, when I send a patch request, this issue does not occur and the page remains unchanged.
I strongly desire that the page should not refresh because it causes the score modal to close and the game to restart abruptly.
let timeRemaining = 5;
let timerStarted = false;
input.addEventListener('keydown', ()=>{
if (!timerStarted) {
timerStarted = true;
let timerInterval = setInterval(()=>{
timeRemaining--;
time.innerText = `${timeRemaining}`;
if (timeRemaining === 0) {
clearInterval(timerInterval);
input.disabled = true;
scoreModal.style.display = 'block';
fetch('http://192.168.0.105:5500/users')
.then(res => res.json())
.then(users => {
const existingUser = users.find(user => user.username === username)
if (existingUser) {
if (score > existingUser.score) {
fetch(`http://192.168.0.105:5500/users/${existingUser.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
score: score
})
})
}
}else{
fetch('http://192.168.0.105:5500/users', {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
score: score
})
})
}
})
}
}, 1000);
}
});