1

i want to click on href and do javascript function to post some value to python and render new template with that data, this is my code.

index.html

<!DOCTYPE html>
<html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
      <a href="#" onclick="myFunction();">Click</a>

<script>
var jsvariable = 'hello world'
    function myFunction(){
        $.ajax({
            url: "/getvalue",
            type: "post", //send it through get method
            data:{'jsvalue': jsvariable},

    })
}
</script>

</body>
</html>

server.py

from flask import Flask, render_template, request, url_for

app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def index():
    return render_template('index.html')

@app.route('/getvalue', methods=['GET','POST'])
def getvalue():
    data = request.form['jsvalue']
    print(data)
    return render_template('index2.html', data=data)

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

Now the data that pass from ajax function to getvalue() in python that work properly but it not render to new template, so how can i fix that.

Kaow
  • 483
  • 2
  • 9
  • 22

1 Answers1

0

Mate you don't even need ajax for this(I even think it's what's making a problem for you, correct me if I'm wrong but ajax makes a background POST request, it's like the template gets rendered to the background, you need a foreground request)

Also bad practice, you put your script before the body, it shouldn't even go in the head but as further down as possible

Why is using onClick() in HTML a bad practice?

server.py

@app.route('/getvalue', methods=['GET','POST'])
def getvalue():
    if request.method=='POST':
        data = request.form['jsvalue']
        return render_template("index2.html", data=data)

index.html

<form action = "/getvalue" method = "POST">
    <input type = "hidden" name = "jsvalue"/>
    <input type = "submit" value = "submit"/>
</form>
<script>
    var jsvariable = 'hello world';
    var el=document.getElementsByName("jsvalue");
    el[0].value=jsvariable;
</script>

index2.html

{{data}}
Filip
  • 138
  • 1
  • 14