0

I have looked at these Stack Overflow links Flask request.get_json() raise BadRequest, Get raw POST body in Python Flask regardless of Content-Type header, and How to get POSTed JSON in Flask?; however, they don't answer my problem. When I use Postman, Python, or curl, my flask code works; however, when I use JavaScript, it doesn't work and I get the BadRequest error. April does print at first; however, the error pops up on the web page. When I try to run json.loads(request.data, strict=False) I get this jinja2 error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I think it might be the Javascript code I am using. Is it possible that concurrently running the request and the form submission might be the problem?

routes.py

@app.route('/calendar/', methods=['GET', 'POST'])
def calendar():
if request.method == 'POST':
    data = request.get_json(force=True)
    print(data['month'])
if form.validate_on_submit():
    pass    

html

<form action="" onsubmit="myFunction()" method="POST">
</form>

function myFunction() {
    var data = "{\"month\":\"April\"}";

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function() {
          if(this.readyState === 4) {
           console.log(this.responseText);
          }
    });
    xhr.open("POST", window.location.href);
    xhr.setRequestHeader("Content-Type", "application/javascript");
    xhr.setRequestHeader("Cookie", "session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjoiNmM5MmIxNmFkYWIyMWZmZjk3MWE4MmJkZTViNTc1M2ZmMDNiY2MxNyJ9.Xo0X5Q.bzl4ihYLaHjUqmiIc6WCwFUOP_8");

    xhr.send(data);
}
EDIT#####
content = request.get_json(silent=True)
    print(content['month'])

prints None

aj3409
  • 186
  • 2
  • 14

2 Answers2

0

I ended up adding to an existing form:

$("#form").submit( function(eventObj) {
                $("<input />").attr("type", "hidden")
                .attr("name", "month")
                .attr("value", "April")
                .appendTo("#form");
            return true;
            });
aj3409
  • 186
  • 2
  • 14
0
$(document).on('click','#texthide',function(){
        
    
        var text = $("#textVal").val();
        var font = $("#font_text").val();
        var color = $("#color_text").val();
        var start_text = $("#start_text").val();
        var end_text = $("#end_text").val();
        var vid_id = new_d
        console.log(text);
        $('body').addClass('addLoader');
        $.ajax({
            url: '/videos/test_text',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            datatype: "json",
            // data: $('#formtext').serialize(),
            data: JSON.stringify(
                
            {   text: $("#textVal").val(),
                font: $("#font_text").val(),
                color:  $("#color_text").val(),
                start_text: $("#start_text").val(),
                end_text: $("#end_text").val(),
                video_id: new_d
            })
          
            
            // onComplete:function(data){
            //     $('body').removeClass('addLoader');
            // }
        });
    });
    
    
    @videos.route("/test_text", methods = ['POST'])
    
    def test_text():
       
        data = request.get_json("")
        print(data)
    
        return "success!"