Need help understanding how to send variables from a Flask route to a JavaScript file and visa versa.
Let's say I have the below Flask route:
@payment.route('/pay/campaign', methods=['GET', 'POST'])
def pay():
user = User.query.get_or_404(campaign.user_id)
amount = 1000
return render_template('payment.html', amount=amount, user=user)
and I want to access the variables amount
and user
in my JavaScript file and send them as a POST request to another Flask route /pay_now
.
These variables are used in the /pay_now
route to create a variable called clientSecret
which I then need to be sent back to my JavaScript file to be used in the confirmCardPayment()
method below. (If there is a way I can define these variables in /pay
and access them directly in /pay_now
without going through the JavaScript, that will work too)
@payment.route('/pay_now', methods=['GET','POST'])
def create_payment():
clientSecret = create_secret(amount, user) #assume this creates secret
return jsonify({"clientSecret": clientSecret})
form.addEventListener('submit', function(ev) {
fetch("/pay_now", {
method: "POST",
body: JSON.stringify({
// not sure how to send amount and user variable to /pay_now
}),
headers: {
"Content-Type": "application/json"
},
})
.then(response => response.json())
.then(data => {
// not sure how to read JSON from /pay_now
});
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: 'Jenny Rosen'
}
}
}).then(function(result) {
if (result.error) {
console.log(result.error.message);
} else {
if (result.paymentIntent.status === 'succeeded') {
}
}
});
});
In summary, I need to:
- Send
amount
anduser
from the/pay
route to my JavaScript file - Then need to pass the
amount
anduser
variable to a Flask API route/pay_now
which creates a variable calledclientSecret
- Finally, fetch the
clientSecret
variable and use it in the JavaScript file
Would be super awesome to get some help on this! Thanks in advance!