Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use data posted from ajax in flask?

I'm having trouble getting data POSTed from jquery ajax.

$('#clickme').click( function() {     var data = save_input(); // data      data['_sid'] = $survey_id;  // survey_id injected from flask     data['_uip'] = $user_ip; // user_ip injected from flask, request.remote_addr      $.ajax({         type : "POST",         url : "{{ url_for('mod.load_ajax') }}",         data: JSON.stringify(data),         contentType: 'application/json;charset=UTF-8',         success: function(result) {             console.log(result);         }     });      console.log(data); }); 

from the code, data is a javascript object like

{     'foo' : 'foo',     'bar' : 'bar',     'fo_' : 42, } 

what I'm trying to do in flask is :

@mod.route('/load_ajax', methods=["GET", "POST"]) def load_ajax():     if request.method == "POST":         # load _sid and _uip from posted JSON and save other data         # but request.form is empty.         # >>> request.form         # ImmutableMultiDict([])          return str(request.form) 

see, the ajax request is made but no data is submitted. I do console.log(data) with ajax so I can see that I really have some meaningful data in data variable in jquery. but request.form in ajax view is empty. Where is my data submitted?

like image 777
thkang Avatar asked Feb 16 '13 09:02

thkang


People also ask

Can we use AJAX in flask?

AXJS(Asynchronous JavaScript and XML) is Asynchronous, so a user can continue to use the application while the client program requests information from the server in the background. Now we'll use jQuery AJAX to post the form data to the Python Flask method.

How would you make an AJAX call to a flask view to return the data to the webpage?

Normally you use an ajax request to return data that you then dynamically display in the page. $. ajax({ url:"/filteredsearch/", type: 'POST', data: json, contentType: 'application/json;charset=UTF-8', success: function(evt) { $("#results"). html = evt.

How do I get data from a flask POST request?

Use request. form to get data when submitting a form with the POST method. Use request. args to get data passed in the query string of the URL, like when submitting a form with the GET method.


1 Answers

Try

 $.ajax({     type : "POST",     url : "{{ url_for('mod.load_ajax') }}",     data: JSON.stringify(data, null, '\t'),     contentType: 'application/json;charset=UTF-8',     success: function(result) {         console.log(result);     } }); 

Then from the server, you can refer to the variables in data like this :

request.json['foo'] 

Since the content type is specified as application/json the data is in request.json

like image 123
phabtar Avatar answered Sep 21 '22 21:09

phabtar