Friday, September 2, 2016

Posting form data via AJAX to Flask route


SERVER-SIDE - PARSE FORM DATA

@app.route('/something', methods=['POST'])
def post_something():
    something=  request.form['something'];
    return json.dumps({'status':'OK','something':something});
SERVER-SIDE - UNIT TEST
def unittest_post_something(self):
    form = dict(something="hey, i'm unit testing you");
    response = self.app.post("/something", data = form)
    self.assertEqual(response.status_code, 200)


CLIENT-SIDE - POST VIA AJAX
var something = "i'm posting via ajax";

$.ajax({
 url: '/something',
 data: $('form').serialize(),
 type: 'POST',
 success: function(response) {
  console.log(response);
 },
 error: function(error) {
  console.log(error);
 }
});


Ref: http://codehandbook.org/python-flask-jquery-ajax-post/ 

No comments:

Post a Comment

There was an error in this gadget