Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Result in Same Page Using python flask

I am using python flask for sending form data into another HTML template. I need to show the result in same page where HTML input form exists. Currently response is being forwarded to next page.

I tried to run via JQuery but still unable to get the result.

app.py

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('index.html')

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

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

index.html

<html>
   <body>
      <form action = "http://localhost:5000/result" method = "POST">
         <p>Name <input type = "text" name = "Name" /></p>
         <p>Physics <input type = "text" name = "Physics" /></p>
         <p>Chemistry <input type = "text" name = "chemistry" /></p>
         <p>Maths <input type ="text" name = "Mathematics" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   <div>
   </div>
    </body>
</html>

Result.html

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

Now the result is displayed at result.html, i need that to be displayed on index.html. Please suggest, how to make this happen.

like image 847
Niraj Avatar asked Apr 07 '26 21:04

Niraj


1 Answers

I know this is an older question, but for anyone else that's possibly interested. All you have to do is change

return render_template("result.html",result = result)

to

return render_template("index.html",result = result)

or to whatever other page you may want to return to. Render_template just returns whatever you ask it to, if you want to return just the data, or something else you can just say

return (data)

or whatever your data is called.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!