I have been working with Flask, HTML and javascript. I have to re-create a pizza site for school. almost everything is going fine, I know how to go to other pages through html and python. But at some point I will be using a button which runs a javascript script which is fine. But when I try to change sites by redirecting it through flask or through html with the line (example): `
<li><a href={{ url_for('store') }}>Menu</a></li>
`
It doesn't work. I also tried redirecting it to the supposed next site since I do setup a site where it receives a json package and all of that works fine. But the only line that isn't working is the redirect line. I got get the message: "GET /payment HTTP/1.1" 200
Now I understood that if I got the message then it means all went fine. However what I wanted to happen didn't happen. So my lack of knowledge and wrong way of thinking blocks me.
I hope I can get answers here. Again, any other way of going to other sites is going well until I want to change sites with the button that uses javascript
Javascript file `
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
for (var i = 0; i < removeCartItemButtons.length; i ) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (var i = 0; i < quantityInputs.length; i ) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
var addToCartButtons = document.getElementsByClassName('shop-item-button')
for (var i = 0; i < addToCartButtons.length; i ) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank you for your purchase')
var cartItems = document.getElementsByClassName('cart-items')[0]
while (cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
}
function quantityChanged(event) {
var input = event.target
if (isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
var button = event.target
var shopItem = button.parentElement.parentElement
var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
addItemToCart(title, price, imageSrc)
updateCartTotal()
}
function addItemToCart(title, price, imageSrc) {
var cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
var cartItems = document.getElementsByClassName('cart-items')[0]
var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
for (var i = 0; i < cartItemNames.length; i ) {
if (cartItemNames[i].innerText == title) {
alert('This item is already added to the cart')
return
}
}
var cartRowContents = `
<div >
<img src="${imageSrc}" width="100" height="100">
<span >${title}</span>
</div>
<span >${price}</span>
<div >
<input type="number" value="1">
<button type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i ) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total (price * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' total
}
`
HTML file `
<!DOCTYPE html>
<html>
<head>
<title>Mario and Luigi's | Menu</title>
<link href="http://fonts.cdnfonts.com/css/italiana" href="{{ url_for('static', filename='css/styles.css') }}">
<meta name="description" content="This is the description">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<script src="{{ url_for('static', filename='JS/store.js') }}" async></script>
</head>
<body>
<header >
<nav >
<ul>
<li><a href={{ url_for('homepage') }}>Home page</a></li>
<li><a href={{ url_for('store') }}>Menu</a></li>
<li><a href={{ url_for('about') }}>About us</a></li>
</ul>
</nav>
<h1 >Mario and Luigi's</h1>
</header>
<section >
<h2 >Popular Pizzas</h2>
<div >
<div >
<span >Margherita</span>
<img src="{{ pizzaMagherita }}">
<div >
<span >$12.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Pepperoni</span>
<img src="{{ pizzaPepperoni }}">
<div >
<span >$14.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Prosciutto E Funghi</span>
<img src="{{ pizzaProsciutto }}">
<div >
<span >$15.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Quattro Stagioni</span>
<img src="{{ pizzaQuattros }}">
<div >
<span >$17.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section >
<h2 >Hot Deals</h2>
<div >
<div >
<span >Star Carlos</span>
<img src="{{ pizzaStarCarlos }}">
<div >
<span >$13.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Nino Bellisimo</span>
<img src="{{ PizzaNinoBel }}">
<div >
<span >$15.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Marinara </span>
<img src="{{ pizzaMarinara }}">
<div >
<span >$10.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section >
<h2 >Luigi's Specials</h2>
<div >
<div >
<span >Luigi's Burger Pizza</span>
<img src="{{ pizzaBurger }}">
<div >
<span >$19.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
<div >
<span >Luigi's Exotic Pizza</span>
<img src="{{ pizzaExotic }}">
<div >
<span >$6.99</span>
<button type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section >
<h2 >CART</h2>
<div >
<span >ITEM</span>
<span >PRICE</span>
<span >QUANTITY</span>
</div>
<div >
</div>
<div >
<strong >Total</strong>
<span >$0</span>
</div>
<button type="button" onclick='myFunction();' >PURCHASE</button>
</section>
<footer>
<header >
<nav >
<ul>
<li><a href={{ url_for('homepage') }}>Home page</a></li>
<li><a href={{ url_for('store') }}>Menu</a></li>
<li><a href={{ url_for('about') }}>About us</a></li>
</ul>
</nav>
<h1 >Mario and Luigi's</h1>
</header>
</footer>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function myFunction() {
const price = document.getElementsByClassName('cart-total-price')[0].innerText;
console.log(price)
const dict_values = {price}
const s = JSON.stringify(dict_values);
console.log(s)
$.ajax({
url:"/test",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
</body>
</html>
`
python file with flask `
import json
from operator import truth
from flask import Flask, jsonify, redirect, request, render_template, template_rendered, session, url_for
from datetime import timedelta
import os
app = Flask(__name__)
app.secret_key = "fresku"
app.permanent_session_lifetime = timedelta(hours=1)
images_folder = os.path.join('static', 'Images')
app.config['UPLOAD_FOLDER'] = images_folder
price = 0
@app.route("/", methods=["POST", "GET"])
def homepage():
if request.method == "POST":
session.permanent = truth
user = request.form["nm"]
session["user"] = user
return redirect (url_for("store"))
else:
if "user" in session:
return redirect (url_for("store"))
return render_template('index.html')
@app.route("/logout")
def logout():
session.pop("user", None)
return redirect(url_for("homepage"))
@app.route("/store", methods=["POST", "GET"])
def store():
MagheritaPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'MargheritaPizza.jpg')
BurgerPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'BurgerPizza.jpg')
ExoticPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'ExoticPizza.jpg')
MarinaraPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'MarinaraPizza.jpg')
NinoBelPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'NinoBelPizza.jpg')
PepperoniPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'PepperoniPizza.jpg')
ProsciuttoPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'ProsciuttoPizza.jpg')
QuattrosPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'QuattrosPizza.jpg')
StarCarlosPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'StarCarlosPizza.jpg')
return render_template("store.html",
pizzaMagherita = MagheritaPizzaPic,
pizzaBurger = BurgerPizzaPic,
pizzaExotic = ExoticPizzaPic,
pizzaMarinara = MarinaraPizzaPic,
PizzaNinoBel = NinoBelPizzaPic,
pizzaPepperoni = PepperoniPizzaPic,
pizzaProsciutto = ProsciuttoPizzaPic,
pizzaQuattros = QuattrosPizzaPic,
pizzaStarCarlos = StarCarlosPizzaPic)
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/test", methods=['POST', 'GET'])
def test():
global price
output = request.get_json()
result = json.loads(output)
#this is a dict type
print(result['price'])
price = result['price']
return redirect (url_for("payment"))
@app.route("/customize")
def customize():
logoPic = os.path.join(app.config['UPLOAD_FOLDER'], 'logo.jpg')
return render_template("custom_page.html",
logo = logoPic)
@app.route("/payment", methods=['POST', 'GET'])
def payment():
global price
return render_template("pay_page.html",
customerPay = price)
@app.route("/track_order")
def tracker():
return render_template("tracker_page.html")
`
I tried redirecting it through the server with the line `
return redirect (url_for("payment"))
And tried changing the page with the line inside html
<li><a href={{ url_for('store') }}>Menu</a></li>
Link doesn't change even though it has to change. but I don't get a error message as well
CodePudding user response:
you need to enclose your href URL in quotes like this:
<li><a href="{{ url_for('store') }}">Menu</a></li>