I have a problem, i cant open render_template after post data with ajax. this is my ajax code.
if ($(this).attr("value") == "button-three") {
var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'negasi')
$.ajax({
data: { metodeSkoring: skoring },
type: 'POST',
url: '/evaluasiModel'
})
}
and this is my server code.
@app.route('/evaluasiModel', methods=['POST',"GET"])
def evaluasiModel():
metodeSkoring = request.form['metodeSkoring']
metodeSkoring = int(metodeSkoring)
return render_template("evaluasiModelKlasifikasi.html", hasilSkoring = metodeSkoring)
i hope after post data ajax to "def evaluasiModel()", I can open render_template "evaluasiModelKlasifikasi.html" and get data metodeSkoring to show in this template.
Why do you need that post functionality? You can simply load the page after getting the value from the user using redirect.
Here is an example how to do so. I simulated a similar scenario. For that I needed
application.py
: as route controllerindex.html
: as main templateevaluasiModelKlasifikasi.html
: as redirected templateapplication.py
:
import json
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def show_index():
return render_template("index.html")
@app.route('/evaluasiModel/<metodeSkoring>')
def evaluasiModel(metodeSkoring):
return render_template("evaluasiModelKlasifikasi.html", hasilSkoring = metodeSkoring)
if __name__ == '__main__':
app.run(debug=True)
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<div id="container">
<input type="text" id="mentodeNegasi" />
<button id="get_button">Get score</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#get_button").on("click",function(){
var skoring = $("#mentodeNegasi").val();
window.location.href = '/evaluasiModel/'+skoring;
})
})
</script>
</body>
</html>
evaluasiModelKlasifikasi.html
<!DOCTYPE html>
<html>
<head>
<title>evaluasiModel</title>
</head>
<body>
<div id="container">
<div id="result">
hasilSkoring: {{ hasilSkoring }}
</div>
</div>
</body>
</html>
Output:
index page:
after redirection:
Demonstration:
You have to add the html code from the response in the success function of the ajax call. You don't specify where you want to add that code, so here you have an example adding it to the body
of your page...
if ($(this).attr("value") == "button-three") {
var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'negasi')
$.ajax({
type: 'POST',
url: '/evaluasiModel'
data: { metodeSkoring: skoring },
dataType: 'html'
success: function(response) {
$('body').append(response);
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With