Issue
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 class="cart-item cart-column">
<img class="cart-item-image" src="${imageSrc}" width="100" height="100">
<span class="cart-item-title">${title}</span>
</div>
<span class="cart-price cart-column">${price}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" 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 class="main-header">
<nav class="main-nav 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 class="Restaurant-name Restaurant-name-large">Mario and Luigi's</h1>
</header>
<section class="container content-section">
<h2 class="section-header">Popular Pizzas</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Margherita</span>
<img class="shop-item-image" src="{{ pizzaMagherita }}">
<div class="shop-item-details">
<span class="shop-item-price">$12.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Pepperoni</span>
<img class="shop-item-image" src="{{ pizzaPepperoni }}">
<div class="shop-item-details">
<span class="shop-item-price">$14.99</span>
<button class="btn btn-primary shop-item-button"type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Prosciutto E Funghi</span>
<img class="shop-item-image" src="{{ pizzaProsciutto }}">
<div class="shop-item-details">
<span class="shop-item-price">$15.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Quattro Stagioni</span>
<img class="shop-item-image" src="{{ pizzaQuattros }}">
<div class="shop-item-details">
<span class="shop-item-price">$17.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">Hot Deals</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Star Carlos</span>
<img class="shop-item-image" src="{{ pizzaStarCarlos }}">
<div class="shop-item-details">
<span class="shop-item-price">$13.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Nino Bellisimo</span>
<img class="shop-item-image" src="{{ PizzaNinoBel }}">
<div class="shop-item-details">
<span class="shop-item-price">$15.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Marinara </span>
<img class="shop-item-image" src="{{ pizzaMarinara }}">
<div class="shop-item-details">
<span class="shop-item-price">$10.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">Luigi's Specials</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Luigi's Burger Pizza</span>
<img class="shop-item-image" src="{{ pizzaBurger }}">
<div class="shop-item-details">
<span class="shop-item-price">$19.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Luigi's Exotic Pizza</span>
<img class="shop-item-image" src="{{ pizzaExotic }}">
<div class="shop-item-details">
<span class="shop-item-price">$6.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span>
</div>
<button class="btn btn-primary btn-purchase" type="button" onclick='myFunction();' >PURCHASE</button>
</section>
<footer>
<header class="main-header">
<nav class="main-nav 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 class="Restaurant-name Restaurant-name-large">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
Solution
you need to enclose your href URL in quotes like this:
<li><a href="{{ url_for('store') }}">Menu</a></li>
Answered By – AudioBaton
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0