Manipulating the DOM using a Flask route in an HTML form

I have a form that allows users to input the names of "Player A" and "Player B". When the user clicks on the "Start Game" button, the game begins by redirecting to a Flask route (/players). I want the "player-text" section to be updated with the player names when the game starts. I've tried implementing this using d3.js but it's not working as expected. The d3.click event is not being recognized. Is there a way to achieve both functionalities successfully? Thank you.

index.html:

<div>
<form method="POST" action="/players" role="form", name="playerform">
    <div class="form-group">
        <label for="playerA">Player A</label>
        <input type="text" class="form-control" id="playerA" name="playerA" placeholder="Player A">
    </div>
    <div class="form-group">
        <label for="playerB">Player B</label>
        <input type="text" class="form-control" id="playerB" name="playerB" placeholder="Player B">
   </div>
   <input type="submit" id="playerform" name="playerform" value="Start Game" class="btn btn-primary btn-lg">
</form>
</div>
<div id = "player-text"> </div>
<script type="text/javascript" src="../static/game.js"></script>

app.py:

@app.route("/players", methods=["GET", "POST"])
def send():
    global ds_game
    if request.method == "POST":
        playerA = request.form["playerA"]
        playerB = request.form["playerB"]
        #return jsonify({"playerA":playerA, "playerB" : playerB})
        return redirect("/index", code=302)

game.js

d3.select("#playerform")
    .on("click", function(){
        console.log("Clicked on player form")
        d3.json("/show",($dict)=> {
            let $scores = $dict["scores"]
            let $player = $dict["player"]
            d3.select("#player_score").remove();
            d3.select("#player-text").append("div").attr("id","player_score")
            .append("p").attr("align","center").html($player)
            .append("p").attr("align","center").html($scores);
        });
    });

Answer №1

The issue arises when submitting the form as the JavaScript-collected data is lost upon page reload.

A solution could be to store the desired values using Flask's session object and access them in the template after redirecting.

Here's an example:

# ...
from flask import session

# Session requires SECRET_KEY to be set
app.config['SECRET_KEY'] = 'something secure'

# ...
def send():
  # ...
  session['players'] = {
    'A': playerA,
    'B': playerB
  }

# ...
def index():
  # ...
  return render_template('template.html', players=session['players'])

You can then reference these values in your template file.

<!-- ... -->
<div id="player-text">
  {% if players %}
  <p>{{ players['A'] }}</p>
  <p>{{ players['B'] }}</p>
  {% endif %}
</div>

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

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

Creating a tool to display mouse coordinates as a pointer on an HTML5 canvas

I'm struggling with mouse coordinates while working on canvas in HTML5. My approach involves using JavaScript for drawing on the canvas. Below is my current code to track the mouse pointer within the canvas: $('#canvasID').mousedown(functi ...

When a node or edge is clicked in Cytoscape, display its attributes in a table format

Hello, I am new to using cytoscape.js and currently working on rendering shallow networks in a Flask App. At the moment, I have managed to display node and edge attributes when hovering over them, but the information is shown in a format that is not very ...

Is there a way to improve scrolling speed on Mobile Safari?

I'm currently working on a project utilizing angularjs and bootstrap, aiming to replicate iOS's navigationController feature. However, I'm encountering speed issues, particularly when scrolling between views on mobile safari iOS. The transi ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Retrieve the information from the API and populate the tables with the data

I'm currently working on fetching API data and displaying it in tables, using mock data for now. Successfully implemented actions and reducers. Managed to call the API but encountered an issue with network calls where I see a blocked response content ...

Update a roster with AJAX following the addition or removal of a user

My goal is to implement two functions: Adding and Deleting a User from the database using Mongoose. However, when I run the code, I receive a 200 OK response but with an empty username. I suspect there might be an issue with the ajax calls. Can anyone hel ...

Safari iOS 8 experiencing issues with loading WebGL image textures

The example mentioned above runs smoothly on all major browsers, including Safari on Mac OS. However, it fails to display the correct image on my iPad running the latest iOS 8. Click here for the example. Similarly, the tutorial provided in the following ...

Dynamic value changes in AngularJS checkboxes controlled by ng-model within controller

I have a page that loads data from a database and displays it in a grid. It has a button to manually refresh the data, as well as a checkbox for automatic refreshing. Below is the HTML code: <div id="TestViewTable" ng-controller="testTableManager" ng- ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...

How does Python interpret arrays from JavaScript?

As part of my API setup, I am sending parameters to a python script. One of these parameters happens to be a JavaScript array. Interestingly, when I check the array in Python, it only shows the first index. Here is the snippet of my Angular JS get request ...

Guidelines for creating a dynamic filter in Prisma js

I am looking to create a dynamic filter based on user input from the frontend. On mapping the data, I found that the object results appear like this: { id: '2', name: 'yuhu' } The keys 'id' and 'name' need to be dyn ...

Is it possible to run a Vue file autonomously, similar to an HTML file

When it comes to running html, we can rely on mainstream browsers such as Chrome. But is there a similar tool for vue files, like the browsers designed for html? ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Is there a restriction on the number of routes available from Google Maps Directions Service?

Utilizing the Google Maps Directions API, I am able to calculate the distance between the current user's location and various stores. Everything functions properly until I exceed 10 store locations, at which point the API ceases to operate due to its ...

Sending a message from a Vue.js application to Contact Form 7 using the Wordpress REST API - a step-by-step guide

I recently added Contact-Form-7 to my WordPress admin panel, which generated an API Endpoint for me at http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms Attempting to send a POST request to this endpoint using the following code: data() ...

Interact with the button through Swipe Left and Right gestures

Is it possible to trigger a button click using JQuery or JavaScript when swiping left or right on two buttons like these? <button id="right" type="button">SWIPE RIGHT</button> <button id="left" type="button">SWIPE LEFT</button> If ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...