Ajax programming is very popular.In this tutorial we are going to see , how to do ajax program in flask framework using json.

To learn json using flask,use the below link.

http://ampersandacademy.com/tutorials/flask-framework-json-example/

Requirement:

1.Jquery Latest

Ajax Syntax


$.ajax({
          url: '/path/to/file',
          type: 'default GET (Other values: POST)',
          dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
          data: {param1: 'value1'},
          success:function(json)
          {
            
          }
        
        });

Here we going to create a simple calculator application. Three input fields-> Tow number fields,One select box to point addition or subtraction ,etc.

flask-framework-ajax-example

Next include your jquery and add the below ajax script to interact with the server(flask framework).It is an button click event.

 


<script type="text/javascript">
    $(document).ready(function() {
      
      //sbtn is id of submit button
      $('#sbtn').click(function(event) {
        /* Act on the event */
        $.ajax({
          url: 'ajaxcalc', //server url
          type: 'POST',    //passing data as post method
          dataType: 'json', // returning data as json
          data: {input1:$('#in1').val(),input2:$('#in2').val(),operator:$('#operator').val()},  //form values
          success:function(json)
          {
            alert(json.result);  //response from the server given as alert message

          }
        
        });
        
      });
    });
    </script>

Then create a flask script(server side programming) to catch all the input field values.


@app.route('/ajaxcalc',methods=['POST', 'GET'])
def ajaxcalc():
    if request.method=='POST':
     input1=int(request.form['input1'])
     input2=int(request.form['input2'])
     operation=int(request.form['operator'])
     result=0
     if operation==1:
        result=input1+input2
     else if operation==2:
        result=input1-input2
     else if operation==3:
        result=input1*input2
     else if operation==4:
        result=input1/input2
     json.dumps({"result":result})
    else:
        return "error"

Note: When catching data at server side of flask, the data type of values are string by default. So you must type cast for other data type ,if required.

Download Source