What causes the page to reload following a JavaScript post request?

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);
  }

});

Answer №1

If you're looking to stop the default behavior of a form submission event, here's a simple way to do it:

const myForm = document.getElementById("myForm");
function preventDefaultAction(event) {
  event.preventDefault();
} 
myForm.addEventListener('submit', preventDefaultAction);

This technique, as seen in How to Prevent Default Form Submission, utilizes the preventDefault() method within the handleForm() function.

Answer №2

In order to avoid the page from refreshing, you can implement an event listener on the form submit event and stop the default behavior of the event by using event.preventDefault(). Here is a sample code snippet that might help you resolve your issue:

const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
  if (time === 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
            })
          })
        }
      })
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

The art of properly indenting coffee script code

I encountered an indentation error in these lines Are there any online validators that can assist me? showAliveTests : (pageIndex, statusFilter) -> data= pageIndex:pageIndex status:statusFilter $.ajax u ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

Guide on how to navigate back to the login page when the access_token in local storage is not defined

Whenever my localStorage turns undefined, I need to redirect the user to the login page. However, this is not working as expected and I'm not sure what the issue is. Below is the code from my PrivateRoute.js: PrivateRoute.js import React from " ...

Guide to setting up a lobby system with Javascript within a Django framework

I am looking to develop a lobby system where users can create rooms, other users can join the room, and the creator of the room will select 9 participants to form 2 teams of 5 players each. Once both teams are finalized, the creator will close the room wit ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Steps for deleting an item from an array based on its property

Seeking advice on how to remove an entire object from an array that contains a specific value. The current array includes multiple objects, as shown below: var cars= [ {key: 'browser', label: 'Chrome'}, {key: 'browser', labe ...

The function history.popstate seems to be malfunctioning, as it is triggered by both the forward and backward navigation buttons in

When I press the back button, I am attempting to retrieve the previous state. Upon inspecting, I noticed that the popstate function is also triggered by the forward button. However, it does not revert to the previous state even though the popstate function ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

When using `mongodb`'s `printjson` function, be aware that the output may include an `ObjectId`

When executing my mongo shell script, the command looks like this: mongo --quiet myscript.js > /tmp/my.json In myscript.js, I utilize printjson. When using mongodb printjson, it outputs ObjectId to my.json, for example: "_id" : ObjectId("5444a932ca62 ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Using Express.js to Query a PostgreSQL Database via URL Parameters

Trying to retrieve specific information from my database via URL query is proving tricky. Currently, the response just displays all individuals in the database. exports.getPersonByName = async (req, res) => { const query = req.query.q try{ const per ...

Is there a way to use JavaScript to open a new window that appears on top of all others?

When you open a window like this alongside a notepad, the new window appears below the notepad. I am curious about how to make a new window open on top of all other windows. Using window.focus() does not seem to do the trick.. setTimeout(function() { ...

Show the selected value in a div when it is changed

How can I use jQuery to display the selected value of an option in an empty div? $(document).ready(function() { let from_select = $('#from_select'); let from_text = $('#from'); //example#1 from_select.on('change', ...

Hide form data upon submission

I have a form and I'm looking to send hidden input using JavaScript. How can this be achieved? Example: <input id="total" type="hidden" value="" name="total" /> When the submit button is clicked, I would like to set its value. ...

Issue with MySQL JSON_SEARCH not functioning properly with Boolean value

I am encountering an issue with the MySQL JSON_SEARCH function, as it does not support searching for boolean values. For reference, please check out this SQL: Below is the database schema: create table if not exists superheroes ( name varchar(32), ...

Deciphering a JSON Array in JavaScript to extract specific components

I have a brief snippet for a JSON array and a JavaScript function that currently returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayi ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...