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'});
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With