1

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!

4
  • You can using javascript set value of mvar to session and get value of session in flask Commented Aug 3, 2017 at 2:01
  • Can you teach me how to do it? I did not learn on session yet Commented Aug 3, 2017 at 2:04
  • I'm not good at JavaScript. Do you know how to set session variable like this. To get session variable in Flask, refer Flask session Commented Aug 3, 2017 at 2:58
  • I'm not sure how it gonna be Commented Aug 3, 2017 at 3:00

2 Answers 2

2

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:

javascript:

$.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);
    }
});

python:

@app.route('/_get_post_json/', methods=['POST'])
def get_post_json():    
    data = request.get_json()

    return jsonify(status="success", data=data)
Sign up to request clarification or add additional context in comments.

4 Comments

but where do I put the name of variable in javascript here?
you don't... a POST is different than a GET in that it has a data payload which will get parsed by that function into the data variable "en masse" (as a python dict in this case which should essentially match the structure of your javascript object)....
I already tried using get_json just now and got the same "None"
I already copied your way of doing it but it printed out "<Response 5 bytes [200 OK]> "
0

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.

10 Comments

it shows this error ----> AttributeError: 'NoneType' object has no attribute 'get'
Update your question with the view function (the function that has v = request.get_json().get('mvar') line )
Change this url: "{{ url_for("get_post_json") }}" to url: "/testing" and then, @app.route("/_get_post_json/") to @app.route("/testing"). Just a try
Are you seing the right edit @Nabin ?? My edit is the most top not above you -_-
Your page url is "/" and ajax request is also in "/". Is that what you want?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.