Search code examples
jqueryajaxflaskpostjsonify

Flask Ajax call getting refreshed after data received to web page


I'm doing a flask project which get a data from a form(only one input) and using ajax POST request I posted it to server and return data on same page. In return I saw that returned data were received to the web page but it get refreshed automatically. I cannot figure out whats happening here. This is my relevant codes.

$(document).ready(function(){
     $("#button").click(function(){
        var userID=$("#userID").val();
        $.ajax({
            url:'/maturity',
            type:"POST",
            data:{userID:userID}
            }).done(function(data){
                 percentageval=data.id;
                 console.log(data.id);

            });
        });
 });
stack_overflow = Blueprint('stack_overflow', __name__)

@stack_overflow.route("/maturity", methods=["POST"])
def maturity():    
    data=request.form["userID"]
    print(data)
    id=46
    return jsonify({"id":46})

Here I created a maturity root to get POST data and return required values. This is default root I'm working with and after ajax call page refresh again to this page.

http://127.0.0.1:5000/stack_overflow

I've check that data has received to server and from jasonify data has returned to web page but problem was page refreshed again after that. Can anyone help me with this.


Solution

  • Do you use the following code within the form?

    <button type="submit">Click Me</button>
    

    Then change the type of the button.

    <button type="button">Click Me</button>
    

    Maybe you should use the 'submit'-event instead of the 'click'-event.