Send data from Javascript → Python and back without reloading the page

Question:

I’m trying to make a stock finance like website where anyone can get fake money and buy stocks. So in the buy page, I am trying to implement a feature where as the user types the stock symbol and the number of shares, in real time, the pricing shows up in the h1 tags that have an id of "render". This can be achived if user input is sent to my app.py and after looking up the price using an api and some math, app.py send the price back to javascript to update the page.
I’ve been trying to use fetch() and AJAX but I don’t understand any of the tutorials or stack overflow questions. Can someone give me a reliable solution and explain it to me?

HTML:

{% extends "layout.html" %}

{% block title %}Buy{% endblock %}

{% block main %}


    <form action="/buy" method="post">
        <div class="mb-3">
            <input class="form-control mx-auto w-auto" autocomplete="off" name="symbol" placeholder="Symbol" value="{{ input_value }}" id="symbols">
        </div>
        <div class="mb-3">
            <input class="form-control mx-auto w-auto" autocomplete="off" autofocus name="shares" placeholder="Shares" id="shares">
        </div>
        <div class="mb-3">
            <button class="btn btn-primary" type="submit">Buy</button>
        </div>

    </form>

    <h1 id="render">

    </h1>

    <script>
    </script>

{% endblock %}

App.py:

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "GET":
        return render_template("buy.html", input_value = "")
    else:
        return render_template("buy.html", input_value = request.form.get("symbol"))

I’m trying to use the function above for rendering the template

Accepting response and sending back information:

@app.route("/show_price", methods=["GET", "POST"])
def show_price():

#logic stuff

return #price
Asked By: Nitro8923

||

Answers:

TL;DR at bottom

I found a solution to the problem by using this as my app.py:

@app.route("/show_price", methods=["GET", "POST"])
@login_required
def show_price():
    # https://www.makeuseof.com/tag/python-javascript-communicate-json/
    data = request.get_json()
    if data[1].isdigit() == True:
        data = jsonify() # the data
        return data
    else:
        return ""

and using fetch() in my javascript:

{% extends "layout.html" %}

{% block title %}Buy{% endblock %}

{% block main %}


    <form action="/buy" method="post">
        <div class="mb-3">
            <input id="symbols"> 
        </div>
        <div class="mb-3">
            <input id="shares">
        </div>

        <h2 id="render">

        </h2>
        <div class="mb-3">
            <button class="btn btn-primary" type="submit">Buy</button>
        </div>
    </form>

<script>
        let input1 = document.getElementById('symbols');
        let input = document.getElementById('shares');
        input.addEventListener('keyup', function(event) {
            value = [
                input1.value, input.value
            ]
            fetch("http://127.0.0.1:5000/show_price",
            {
            method: 'POST',
            headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json'
            },
            body: JSON.stringify(value)}).then(res =>{
            if(res.ok){
                return res.json()
            } else {
                document.querySelector('h2').innerHTML = "Keep typing...";
            }
            }).then(jsonResponse=>{
                word = "That would be " + jsonResponse
                document.querySelector('h2').innerHTML = word;
            })
            .catch((err) => console.error(err));

        });
    </script>
{% endblock %}

so as the user is typing in the the shares field the event listener will get the symbols and shares fields, use fetch() to get the data over to def show_price() with a jsonified array of symbol and shares. If there is an error the div id="render" will display "Keep typing". After python gets the information it will look it up using a function, then it will return the price of the shares in json format. Then javascript will get the data and use some javascript to change the html.

TL;DR

Basically I used fetch() to get the data to python, did some algorithm stuff and python return it to javascript. https://www.makeuseof.com/tag/python-javascript-communicate-json/ is really useful in teaching you how to use fetch().

Answered By: Nitro8923
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.