2

Let me preface this by saying there are endless threads that describe the issue WITH a button involved. Usually it's solved by just calling event.preventDefault() on the event you pass in. But what if the post request is called after something happens that isn't within the user's control, for instance, after a certain amount of frame?

makeScore (userId, gameId, time) {
      fetch('http://localhost:3000/scores', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          time: time,
          user_id: userId,
          maze_id: gameId
        })
      }).catch(error => console.log('ERROR'))
    };

    loadNextLevel(option) {

        console.log("Load Next");

        //  Making a score
        clearInterval(this.interval);
        this.time = document.getElementById('timer_text').innerHTML;
        this.makeScore(this.userId, this.gameId, this.time);
        console.log("Score made");

        if (this.GAMESTATE != GAMESTATE.GAMEOVER) {

        console.log(this.gameObjects);
        document.getElementById('timer_text').innerHTML = "Time"
        this.gameObjects = []
        this.gameIndex += 1;

        console.log(this.gameIndex, this.maxMazes);

        if (option == "new") {
          this.gameIndex = 0;
        }
      }

      if (this.gameIndex >= this.maxMazes) {
        this.gameEnd();
        return;
      }

With this code, I want to call makeScore only after loadNextLevel is called, and that is only getting called when a level is completed. But, currently the score is saved, and the page is refreshed. How can I prevent this refresh?

Edit: added scores controller below

class ScoresController < ApplicationController

    def index
        scores = Score.all
        render json: scores
    end

    def show
        score = Score.find(params[:id])
        render json: score
    end

    def create
        if (params[:user_id] && params[:maze_id])
            user = User.find_by(id: params[:user_id])
            maze = Maze.find_by(id: params[:maze_id])
            score = user.scores.build(time: params[:time], username: user.username)
            maze.scores << score
        end
    end

end

Edit #2 - Adding the function that it apparently gets stuck on after the fetch is completed.

function setLoggedOutUI() {
  console.log("Log out UI set");
  document.getElementById("timer_text").style.display = "none";
  document.getElementById("logInButton").innerHTML = "Log in";
  document.getElementById("userInfo").innerHTML = "Please Log in to play";
  document.getElementById("logInField").style.display = "inline-block";
  document.getElementById("play").innerHTML = "Log in";
  document.getElementById("scores").style.display = "none";
  document.getElementById("usernameText").style.display = "inline";
  uiSwitch = false;
}
  • 2
    A page refresh isn't going to happen from an ajax call, which fetch is. What exactly are you saying is triggering the page refresh? And when you say "refresh" are you meaning that the page reloads, or just that data changes? – Taplar Aug 21 '20 at 19:58
  • @Taplar I mean the page reloads. The function is called within an update function that runs every millisecond, and if the cursor is in the finish area with no coins on the map, it's triggered. I have no idea why it reloads. – Hans Foster Aug 21 '20 at 20:11
  • 1
    Then something outside of this logic is making it reload. I don't see anything with this logic that should cause a page reload. – Taplar Aug 21 '20 at 20:12
  • I'm so confused. Within the console, it just says after 10 milliseconds passed the call, Navigated to http://127.0.0.1:5500/maze-generator-front-end/index.html. If I just do a get request, it will not navigate anywhere. – Hans Foster Aug 21 '20 at 20:18
  • Would it be standard to run index.js after a post request even if the code would be elsewhere at the time of running it? That appears to be happening before it's getting refreshed, or at least before console logs the navigation path.... – Hans Foster Aug 21 '20 at 20:50
  • A post request is only going to perform whatever logic is at the server endpoint you are calling, and then any logic that are tied to the resolution of the ajax promise. – Taplar Aug 21 '20 at 20:56
  • I'm just not seeing the code that would cause it to refresh itself. I'll add the scores controller too in case you see something there to the post. – Hans Foster Aug 21 '20 at 22:12
  • 1
    The whole point of AJAX is that it *doesn't* automatically reload the page. It just does what your JavaScript tells it to do. – Barmar Aug 21 '20 at 22:20
  • @Barmar that's what I thought. What javascript would cause it to reload the page with the ajax request but not without it? – Hans Foster Aug 21 '20 at 23:04
  • I can't think of anything that would only reload with the AJAX request, – Barmar Aug 21 '20 at 23:22
  • Maybe [this question](https://stackoverflow.com/questions/11194971/break-when-window-location-changes) would be helpful in debugging it. – Barmar Aug 21 '20 at 23:23
  • The network tab shows everything working until a function called loggedOutUI, which again does not look too suspicious (updated post with it). The network tab log shows all 304 status, until the 101 websocket status while trying to run loggedOutUI. Other than that, those threads have not yet lead me in the right direction. – Hans Foster Aug 22 '20 at 00:11

1 Answers1

3

I had this same issue, in my case the problem was caused by the live server. I had in the same folder the client (HTML,CSS, JS, etc.) and the database (I was using the json-server extension). The problem was that the live server was detecting the changes in the db.json file. When fetch post or delete data, it triggers the live reload in the live server extension. So I solved it by dividing the folders and opening them separately in vs code, then, inside the client folder, run live server and it worked perfectly. More details here