When I send post request JSON to server username and score page being refreshed. Patch request does not have this problem page not being refreshed.
I need the page should not be refreshed because my score modal closes and the game restarts.
let vaxt = 5;
let timeStart = false;
input.addEventListener('keydown', ()=>{
if (!timeStart) {
timeStart = true;
let timer = setInterval(()=>{
vaxt--;
time.innerText = `${vaxt}`;
if (vaxt === 0) {
clearInterval(timer);
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);
}
});
2
Answers
On the method that is firing the fetch, try to recieve an event and then setting it to prevent default by using:
On this example from Stop form refreshing page on submit, handleForm() is the method being called
To prevent the page from refreshing, you can add an event listener to the form submit event and prevent the default behavior of the event using event.preventDefault(). An example of how it would look, see if you can solve your problem: