0

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:

  1. Send amount and user from the /pay route to my JavaScript file
  2. Then need to pass the amount and user variable to a Flask API route /pay_now which creates a variable called clientSecret
  3. 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!

Cole S
  • 408
  • 1
  • 3
  • 13
  • The `data` should be available where you had `// not sure how to read JSON from /pay_now`? Might be useful to include a `console.log(data)` to see what's there inside your browser's debug console to verify. – metatoaster Oct 09 '20 at 02:39
  • Okay thanks, will check that. Do you know how to access `amount` and `user` in the JavaScript from the `/pay` route? – Cole S Oct 09 '20 at 02:41
  • {{amount}} or {{user}} I believe this is what you need https://stackoverflow.com/questions/11178426/how-can-i-pass-data-from-flask-to-javascript-in-a-template – BOB Oct 09 '20 at 04:52
  • there could be a better way ... but you can do as `"{{ amount }}" and "{{ user }}"` – KcH Oct 09 '20 at 09:53

0 Answers0