Reputation: 81
I'm a complete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is completely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
@app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
Upvotes: 1
Views: 10163
Reputation: 11776
Instead of using
v = request.form.get('mvar', type=int)
Use this
v = request.get_json().get('mvar')
Once you print v then you should get it.
Upvotes: 0
Reputation: 5362
The Request.get_json() method is what you are looking for in your Flask code.
data = request.get_json()
edit here is the exact pattern i use which works:
$.ajax({
type: "POST",
url: "{{ url_for("get_post_json") }}",
contentType: "application/json",
data: JSON.stringify({hello: "world"}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
@app.route('/_get_post_json/', methods=['POST'])
def get_post_json():
data = request.get_json()
return jsonify(status="success", data=data)
Upvotes: 2