I'm making a flask application. The user submits a form, which is sent to flask. Something is done, and I'm trying to send the results back to html with jquery( defined as temp). I want to use jquery because eventually I want to dynamically append to an unordered list from flask.
@app.route('/')
def index():
return render_template("index.html")
@app.route('/search', methods=['GET', 'POST'])
def search_form():
print(request.form)
x = request.form['id']
a = Vbulletin(x)
#a.reg_ver()
def result_gen():
return a.reg_ver()
result_gen()
temp = []
for s in result_gen():
text = s
print(text)
temp.append(text)
print(temp)
return jsonify(temp)
forumsearch.js:
$(document).ready(function(){
$("#submit").on('click',function(e){
e.preventDefault();
req = $.ajax({type: "POST",
url: "/search",
data: { id: $("#searchinput").val()},
//const resultList = document.getElementById("resultList")
});
req.done(function(e){
alert("POST was sent.");
$('#resultList').text(temp);
});
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>UserFind Home</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
<script type="text/javascript" src="{{ url_for('static', filename='forumsearch.js') }}"></script>
</head>
<body>
<nav>
<ul id="navlist">
<h1>Userfind</h1>
<li><a class="btn" href="#home">Home</a></li>
<li><a class="btn" href="#contact">Contact</a></li>
<li><a class="btn" href="#about">About</a></li>
<form method="POST" name="searchbar">
<ul id="navsearch">
<li class="search">
<input type="text" id="searchinput" name="searchinput" placeholder="Search for User here. Must be atleast 5 characters long.">
</li>
<li><button type="submit" id="submit" class="btn-default">Submit</button></li>
</ul>
</form>
</ul>
</nav>
<script>
var btnContainer = document.getElementById("navlist");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className += " active";
});
}
</script>
<p id="resultList">{{ temp }}</p>
<div class="footer">
<p>©2019 Userfind</p>
</div>
</body>
</html>
I've attempted to write the code so when POST request is done is jquery takes the 'temp' variable and passes it to html. but 'temp' is not in the html source code.
And the console says:
ReferenceError: temp is not defined forumsearch.js:11:13
which is this line:
$('#resultList').text(temp);
So how can I define temp so it shows up on the page( using jquery)?