How can I send Json Data from javaScript to Flask

10,247

you need to remove the action field on your form because when the user clicks the button action is called session may not be set

<form method="post" role="form">
<button class="btn btn-primary" name = "submit" id = "submit">submit</button>
</form>

then on ajax you need to set to window location on success

  <script>
         $(document).ready( function() {
        $('#submit').click(function() {
           var formdata = serialize();
           $.ajax({
                 type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formdata),
                dataType: 'json',
                url: 'http://192.168.57.223:5000/createform',
                success: function (e) {
                    console.log(e);
                    window.location = "http://192.168.57.223:5000/preview";
                },
                error: function(error) {
                console.log(error);
            }
            });
        });
  });
    </script>

then your python script should look like this you need to say that you took the value and ajax would set the desired window location

@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        asd = request.json
        print(asd)
        session['formdata'] = asd
        if 'formdata' in session:
            return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
    return render_template("createform.html")
Share:
10,247
Batuhan Coşkun
Author by

Batuhan Coşkun

Updated on June 08, 2022

Comments

  • Batuhan Coşkun
    Batuhan Coşkun almost 2 years

    I am trying to make a Dyanmic Form Builder. After the building process I am trying to put all form data in a JsonObject by a script and pass it to a flask view so I can show them to the user. But I couldn't set it up correctly. Here is the button calls the javascript

    <form action="/preview" method="post" role="form">
    <button class="btn btn-primary" name = "submit" id = "submit">submit</button>
    </form>
    

    And here is the script that I make the ajax call.

    <script>
         $(document).ready( function() {
            $('#submit').click(function() {
               var formdata = serialize();
               $.ajax({
                     type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formdata),
                    dataType: 'json',
                    url: 'http://192.168.58.206:5000/index',
                    success: function (e) {
                        console.log(e);
                    },
                    error: function(error) {
                    console.log(error);
                    }
                    });
                });
            });
    </script>
    

    And here is how I try to render in flask python.

    @app.route('/', methods=['GET', 'POST'])
    @app.route('/index', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            asd = request.json
            session['formdata'] = asd
            if 'formdata' in session:
                return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
        return render_template("index.html")
    
    @app.route('/preview', methods=['GET', 'POST'])
    def preview():
        if 'formdata' in session:
    
            renderedform = formbuilder(json.dumps(session['formdata']))
            renderedform = renderedform.renderform()
            session.pop('formdata')
            return render_template("asd.html",renderform = renderedform)
        return "Error"
    

    My renderdorm() method takes the json object as parameter and creates the corresponding html blocks for the form.

    But when I run it this way,sometimes button action directs me to the /preview route before the scripts runs and creates the json object. So this causes formdata of the session to be None.

    Any ideas how can I pass that json object to render in preview ?