Reputation: 151
Basically I want the code below to put the "search" from the backend to the frontend.
I am having trouble getting my flask app to pass data from the back end to the front end using templates and a simple flask structure.
I am open to suggestions for better ways. Also @ Daniel Mesejo has been a great help so far in my learning about Flask and ajax/jquery.
here is my app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
entries = json.dumps(scrape("video games"))
return render_template('index.html', entries= entries)
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
if request.method == "POST":
#data = request.form("blah")
#print("blah")
search = request.get_json()
#new_search = json.dumps(scrape(data))
return jsonify(search)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
here is my index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
<form class = "form" action="" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p>you searched: {{search}} </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
alert(value);
$.ajax({
type: 'POST',
url: "parse_data",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(JSON.stringify(data));
}
});
});
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
//document.getElementById("user").innerHTML =
//obj;
//"Name: " + obj.product_name + "<br>" +
//"Location: " + obj.product_link;
</script>
</body>
</html>
Upvotes: 3
Views: 6859
Reputation: 61900
To achieve that change the function you pass to success
like this:
success: function (data) {
$("#search-query").text("you search: " + data["text"]);
}
and change the <p>
element to <p id="search-query"> you searched: </p>
.
To learn more about Flask and web development in general, I suggest the Flask Mega Tutorial, here.
Upvotes: 5