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 ?