Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send Json Data from javaScript to Flask

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 ?

like image 677
Batuhan Coşkun Avatar asked Jan 25 '17 09:01

Batuhan Coşkun


People also ask

Can JavaScript write to a JSON file?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.

Can Flask be used with JavaScript?

Flask is an open source tool with 45.2K GitHub stars and 12.7K GitHub forks. Here's a link to Flask's open source repository on GitHub. Airbnb, Instagram, and reddit are some of the popular companies that use JavaScript, whereas Flask is used by Netflix, reddit, and Lyft.


1 Answers

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")
like image 83
Alper Fırat Kaya Avatar answered Oct 10 '22 09:10

Alper Fırat Kaya