I can't figure out why my search function on pythonanywhere isn't working please help. Attached is the instructions and json file. Here's my flask_app.py from flask import Flask, render_template, jsonify, request import json app = Flask(__name__) @app.route('/') def index(): return render_template('apartmentsearch.html') @app.route('/catalog/') def catalog(search): f = open('/home/pcasseus/data/apartments.json') apartments = json.load(f) query = request.args.get('searchField', '') bedrooms = request.args.get('bedrooms', '') sort = request.args.get('sort', '') filtered_apartments = [] for apt in apartments: if query.lower() in apt['Title'].lower() or query.lower() in apt['Description'].lower(): if bedrooms == '1+' and apt['Number of Bedrooms'] < 1: continue if bedrooms == '2+' and apt['Number of Bedrooms'] < 2: continue filtered_apartments.append(apt) if sort == 'price-ascending': filtered_apartments.sort(key=lambda x: x['Monthly Rent']) elif sort == 'price-descending': filtered_apartments.sort(key=lambda x: x['Monthly Rent'], reverse=True) return jsonify(filtered_apartments) if __name__ == '__main__': app.run(debug=True) Here's my script.js function loadDoc(url, func) { let xhttp = new XMLHttpRequest(); xhttp.onload = function() { if (xhttp.status != 200) { console.log("Error"); } else { func(xhttp.response); } } xhttp.open("GET", url); xhttp.send(); } function apartment_search() { let searchField = document.getElementById("searchField").value; let bedrooms = document.getElementById("bedrooms").value; let sort = document.getElementById("sort").value; // Construct the URL with query parameters let url = `http://pcasseus.pythonanywhere.com/catalog/${searchField}?bedrooms=${bedrooms}&sort=${sort}`; loadDoc(url, apartment_search_results); } function apartment_search_results(response) { let data = JSON.parse(response); let results = data["result"]; let temp = ''; for (let i = 0; i < results.length; i++) { let apartment = results[i]; temp += ""; temp += "Title: " + apartment.Title + ""; temp += "Description: " + apartment.Description + "" temp += "Number of Bedrooms: " + apartment['Number of Bedrooms'] + ""; temp += "Monthly Rent: " + apartment['Monthly Rent']; temp += ""; } temp += ''; let divResults = document.getElementById('divResults'); divResults.innerHTML = temp; } Here's my apartmentsearch.html Apartment Search Search: Number of Bedrooms: Sort By: Search Type in a search and hit search button...
I can't figure out why my search function on pythonanywhere isn't working please help. Attached is the instructions and json file.
Here's my flask_app.py
from flask import Flask, render_template, jsonify, request
import json
app = Flask(__name__)
@app.route('/')
def index():
return render_template('apartmentsearch.html')
@app.route('/catalog/<search>')
def catalog(search):
f = open('/home/pcasseus/data/apartments.json')
apartments = json.load(f)
query = request.args.get('searchField', '')
bedrooms = request.args.get('bedrooms', '')
sort = request.args.get('sort', '')
filtered_apartments = []
for apt in apartments:
if query.lower() in apt['Title'].lower() or query.lower() in apt['Description'].lower():
if bedrooms == '1+' and apt['Number of Bedrooms'] < 1:
continue
if bedrooms == '2+' and apt['Number of Bedrooms'] < 2:
continue
filtered_apartments.append(apt)
if sort == 'price-ascending':
filtered_apartments.sort(key=lambda x: x['Monthly Rent'])
elif sort == 'price-descending':
filtered_apartments.sort(key=lambda x: x['Monthly Rent'], reverse=True)
return jsonify(filtered_apartments)
if __name__ == '__main__':
app.run(debug=True)
Here's my script.js
function loadDoc(url, func) {
let xhttp = new XMLHttpRequest();
xhttp.onload = function() {
if (xhttp.status != 200) {
console.log("Error");
} else {
func(xhttp.response);
}
}
xhttp.open("GET", url);
xhttp.send();
}
function apartment_search() {
let searchField = document.getElementById("searchField").value;
let bedrooms = document.getElementById("bedrooms").value;
let sort = document.getElementById("sort").value;
// Construct the URL with query parameters
let url = `http://pcasseus.pythonanywhere.com/catalog/${searchField}?bedrooms=${bedrooms}&sort=${sort}`;
loadDoc(url, apartment_search_results);
}
function apartment_search_results(response) {
let data = JSON.parse(response);
let results = data["result"];
let temp = '<ul>';
for (let i = 0; i < results.length; i++) {
let apartment = results[i];
temp += "<li>";
temp += "<strong>Title:</strong> " + apartment.Title + "<br>";
temp += "<strong>Description:</strong> " + apartment.Description + "<br>"
temp += "<strong>Number of Bedrooms:</strong> " + apartment['Number of Bedrooms'] + "<br>";
temp += "<strong>Monthly Rent:</strong> " + apartment['Monthly Rent'];
temp += "</li>";
}
temp += '</ul>';
let divResults = document.getElementById('divResults');
divResults.innerHTML = temp;
}
Here's my apartmentsearch.html
<!DOCTYPE html>
<html>
<head>
<title>Apartment Search</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<script src="{{ url_for('static', filename='script.js') }}"></script>
</head>
<body>
<div>
Search: <input type="text" id="searchField">
<label for="bedrooms">Number of Bedrooms:</label>
<select id="bedrooms-dropdown">
<option value="">Any</option>
<option value="1">1+</option>
<option value="2">2+</option>
</select>
<label for="sort">Sort By:</label>
<select id="sort-dropdown">
<option value="none">None</option>
<option value="price-ascending">Ascending</option>
<option value="price-descending">Descending</option>
</select>
<button onclick="apartment_search()">Search</button>
</div>
<div id="divResults">
Type in a search and hit search button...
</div>
</body>
</html>
Step by step
Solved in 3 steps