How to redirect to an external url with parameters and POST method?

20.1k views Asked by At

I want save form data before submit to action url in flask

<form action="" method="POST">
    <input type="hidden" name="PAYEE_ACCOUNT" value="U1234567">
    <input type="hidden" name="PAYEE_NAME" value="Name">
    <input type="text"   name="PAYMENT_AMOUNT">
    <input type="submit" name="PAYMENT_METHOD" />
</form>

I can submit this form, but i want save form data before submit

View:

@mod.route('/payment/', methods=['GET', 'POST'])
def payment():
    if request.method != "POST":
        return render_template('form.html')

    form = request.form

    form_data = {'PAYEE_ACCOUNT': form['PAYEE_ACCOUNT'],
                 'PAYEE_NAME': form['PAYEE_Name'],
                 'PAYMENT_AMOUNT' : form['PAYMENT_AMOUNT']
                 }

    # Save Data

    import urllib
    params = urllib.urlencode(form_data)

    url = 'http://www.example.com'
    return redirect(url, params)

Please help me

3

There are 3 answers

0
Majid Zandi On BEST ANSWER

I've solved this problem by using JavaScript.

First, sending the data to server.

JavaScript code:

<script type="text/javascript">
  var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};

  $(function() {
    $('#PAYMENT_METHOD').bind('click', function() {
      $.getJSON($SCRIPT_ROOT +'/credit/save_transaction', {
        PAYMENT_ID: $('input[name="PAYMENT_ID"]').val(),
        PAYMENT_AMOUNT: $('input[name="PAYMENT_AMOUNT"]').val(),
        SUGGESTED_MEMO: $('input[name="SUGGESTED_MEMO"]').val()
      }, function(data) {
         if (data.result == 'ok') {
            $('#form_payment').submit();
         }
      });
      return false;
    });
  });
</script>

Then, saving the data and returning result.

View code:

@mod.route('/save_transaction', methods=['GET', 'POST'])
def save_transaction():
    follow_num = request.args.get('PAYMENT_ID')
    amount = request.args.get('PAYMENT_AMOUNT')
    memo = request.args.get('SUGGESTED_MEMO')

    #Save Data

    return jsonify(result='ok')
1
Rishi Dua On

You need to use flask.redirect

flask.redirect(location, code=302)

Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.

Parameters:
location – the location the response should redirect to. code – the redirect status code. defaults to 302.

Sample code:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

see the documentation on flask docs.

0
hamidfzm On

Sending a 307 status code instead of 302 should tell the browser to preserve the used HTTP method and thus have the behavior you're expecting. Your call to redirect would then look like this:

@mod.route('/payment/', methods=['GET', 'POST'])
def payment():
    if request.method != "POST":
        return render_template('form.html')

    form = request.form

    form_data = {'PAYEE_ACCOUNT': form['PAYEE_ACCOUNT'],
                 'PAYEE_NAME': form['PAYEE_Name'],
                 'PAYMENT_AMOUNT' : form['PAYMENT_AMOUNT']
                 }

    # Save Data

    url = 'http://www.example.com'
    return redirect(url, code=307)