darkpirate
darkpirate

Reputation: 722

Jquery sending a json with post

i have a flask server that take a json formatted as a string and return it (just for testing purposes) wich works when i send the request via curl like this:

curl  -X POST -d data='{"username":"xyz","password":"xyz"}' http://localhost:5000/raw_query

but when i try with this simple jquery script:

    $.post("http://127.0.0.1:5000/raw_query", '{"username":"xyz","password":"xyz"}', function(data, textStatus) {
        if(textStatus == 'success')
        {
            console.log(data)
        }
        else
        {
            console.log(textStatus)
        }
    });

i get a 400 bad request error:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

to add more detail: this is the flask code that executes the request:

@app.route('/raw_query', methods = ['POST'])
   def raw_query():
     data = json.loads(request.form['data'])
     return jsonify(data)

i really can't think of a possible reason for it, but then again i'm quite a rookie with jq so probably i'm missing something... any help would be much appreciated

Upvotes: 0

Views: 71

Answers (2)

Barmar
Barmar

Reputation: 782305

The problem is that you're not sending the parameter name data. You're just sending the JSON string as the raw parameter, not the value of the data POST parameter.

$.post("http://127.0.0.1:5000/raw_query", {
    data: '{"username":"xyz","password":"xyz"}'
}, function(data, textStatus) {
if(textStatus == 'success')
    {
        console.log(data)
    }
    else
    {
        console.log(textStatus)
    }
});

Upvotes: 0

user2560539
user2560539

Reputation:

Try alter a bit your code as in the below example (have not tested this). Format your data (A plain object or string that is sent to the server with the request) like:

 $.post("http://localhost:5000/raw_query", {data:JSON.stringify({username:"xyz",password:"xyz"})}, function(data, textStatus) {
        if(textStatus == 'success')
        {
            console.log(data)
        }
        else
        {
            console.log(textStatus)
        }
    });

Upvotes: 1

Related Questions