0

Could you please help me with an issue with receiving array data on flask?

flask route

@app.route("/grab_checkboxes", methods = ["GET", "POST"])
def grab_checkboxes():
    print("Grabbing 1 or more checkboxes that are true!")
    data = request.get_json()
    print(data)
    return "1"

jquery and ajax code

{% extends "layout.html" %}
{% block content%}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
  $("document").ready(function() {
  var checked_codes = [];
  $("#checked_codes_button").mouseenter(function(){
    $.each($("input[type='checkbox'][name='record_code']:checked"), function(){ 
                checked_codes.push($(this).val());
            });
            console.log(checked_codes)
    });
  $("#checked_codes_button").click(function() {
      $.ajax({
        url: '/grab_checkboxes',
        data: JSON.stringify(checked_codes),
        type: 'POST',
        success: function(response) {
          console.log(response);
          console.log(checked_codes);
        }
      });
  });
});
</script>
  <table>
    {% for k1, v1 in list_to_print.items() %}
      {% for k2, v2 in code2descr.items() %}
        {% if k1 == k2 %}
          <tr>
              <td><input type="checkbox" checked name="record_code" value="{{k1}}" ></td>
              <td> {{ v1 }} </td>
              <th> {{ k1 }} </th>
              <td> {{ v2[0] }} </td>
              <td> {{ v2[2] }} </td>
              <td> {{ v2[1] }} </td>
          </tr>
        {% endif %}
      {% endfor %}
    {% endfor %}
  </table>
  <form action="/grab_checkboxes" method="post" id="checked_codes_button">
  <button type="submit">submit</button>
  </form>
{% endblock content %}

After clicking the button I can see that the console prints correct values, however in Python print(data) I see that I received None.

Thank you.

3
  • If you plan to send json you need to set appropriate contentType. The default is form-encoded not application/json Commented Jul 11, 2019 at 0:21
  • could you please be more specific? where should I set the contentType? In flask? or in ajax? Commented Jul 11, 2019 at 0:23
  • In ajax api.jquery.com/jQuery.ajax Commented Jul 11, 2019 at 0:26

1 Answer 1

1

Since you are wanting to send json you need proper contentType set in $.ajax

Try adding:

$.ajax({
    url: '/grab_checkboxes',
    contentType: 'application/json; charset=utf-8`,
    ....
Sign up to request clarification or add additional context in comments.

Comments

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.