Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jquery $.ajax to call a server side function on Flask [duplicate]

Tags:

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: "[email protected]"},
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'});
like image 357
Rimo Avatar asked Sep 27 '17 23:09

Rimo


1 Answers

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'})
like image 185
Joran Beasley Avatar answered Sep 22 '22 01:09

Joran Beasley