-1

I'm trying to send a simple POST request containing some data. I'm processing the request in flask and trying to return the same data. But it's always returning 'None'.

AJAX

$(function(){
$('.btn').click(function(){
var roll_no = $(this).parent().parent().children(':first-child').html();
$.ajax({
  url: '/delete_student',
  data: {id: roll_no},
  type: 'POST',
  dataType: "text",
  success: function(response){
    console.log(response);
  },
  error: function(error){
    console.log(error);
  }
  });
 });
});

FLASK

@app.route('/delete_student',methods=['GET','POST'])
def delete_student():
if request.method=='POST':
    roll_no = request.args.get("id")
    return str(roll_no)
sujeet
  • 3,480
  • 3
  • 28
  • 60

1 Answers1

1

request.args contains the URL parameters for GET requests. Since you're using a POST request, it will default to None. You should instead use request.form as in:

if request.method=='POST':
    roll_no = request.form['id']
    return str(roll_no)

See the Flask documentation for more information on the request object.

eicksl
  • 852
  • 8
  • 8
  • I thought `request.form` would only work when a form was submitted, but it turned out it woud work for any POST request. So, `request.args` contains the data in json format when a GET request is sent, and `request.form` contains the data in json format when a POST request is sent? – sujeet Feb 04 '18 at 09:49
  • Actually, request.args contains a MultiDict of the parsed contents of the query string, and request.form is a MultiDict of the form values sent in the POST request. These and JSON are different data types. For example, you cannot save a dictionary or MultiDict to a file or send it in an HTTP request. You should think of JSON as a data format rather than an abstract data type. – eicksl Feb 04 '18 at 10:09
  • To be honest, I need to read some more. I'm little bit confused, and I can't ask you everything here.Would you,please, give me any useful link or any other source on this topic? Flask documentation doesn't help. – sujeet Feb 04 '18 at 10:09
  • Just try googling. There is probably a useful blog or tutorial out there somewhere. :) – eicksl Feb 04 '18 at 10:12