Get VAR values from script in Html to Python

Question:

I am trying to make a simple project using flask in Python and Html and I want values from script in Html to Python but i am not able to do it. Can anyone please help me…

Html Code

        <script>
            var index, table = document.getElementById("table");
            for(var i=1; i<table.rows.length; i++){
                table.rows[i].cells[3].onclick=function(){
                    index = this.parentElement.rowIndex; 
                    table.deleteRow(index);
                    console.log(index)
                };
            }
        </script>       
    </form>

Python

rows = [["Harish", "10", "Harish@1"], ["Ramesh", "3", "12345678"]]

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    global headers, rows

    return render_template('table.html', headers=headers, data=rows)

if __name__ == '__main__':
    app.run(debug=True)```
Asked By: ImMortal_05

||

Answers:

You can create a flask view that receive the index var from js and use it in Python.

python:

rows = [["Harish", "10", "Harish@1"], ["Ramesh", "3", "12345678"]]

from flask import Flask, render_template, request

app = Flask(__name__)

index = None

@app.route('/', methods=['GET', 'POST'])
def home():
    global headers, rows

    return render_template('table.html', headers=headers, data=rows)

@app.route('/index', methods=['POST'])
def get_data():
    index = request.args.get("index") #now you can use var index inside python

if __name__ == '__main__':
    app.run(debug=True)

HTML code:

<script>
            var index, table = document.getElementById("table");
            for(var i=1; i<table.rows.length; i++){
                table.rows[i].cells[3].onclick=function(){
                    index = this.parentElement.rowIndex; 
                    table.deleteRow(index);
                    sendIndex(index);
                };
            }
            function sendIndex(index){
var requestOptions = {
  method: 'POST',
  redirect: 'follow'
};

fetch(`http://127.0.0.1:8000/index/?index=${index}`, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));}
        </script>       
Answered By: Super sub
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.