6

I want to call a server side function using Ajax.

I have found a straightforward example for PHP in this post. I think the community would improve if we could include this very same example but for Python / Flask MVC framework.

This is the ajax code on the View side, called test.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
function create () {
$.ajax({
url:"test1", //the page containing python script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
success:function(result){
console.log(result.abc);
      }
    });
   } 
</script>

And this would be the Python code on the Controller:

@app.route('/test', methods=['GET','POST'])
    def test():
        return render_template("test.html", brand = brand)

@app.route('/test1', methods=['GET','POST'])
    def test1():
        if registration == "success":
            return json.dump({"abc":'successfuly registered'});
Rimo
  • 555
  • 1
  • 8
  • 18

1 Answers1

5

Remove the arguments to the view function. Access posted data with request.form. Return a JSON response using jsonify. The view must return a response from each execution path.

@app.route('/test1', methods=['GET', 'POST'])
def test1():
    if request.form.get('registration') == 'success':
        return jsonify({'abc': 'successfuly registered'})

    return jsonify({'abc': 'registration unsuccessful'})
davidism
  • 121,510
  • 29
  • 395
  • 339
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179