Home > Net >  Ajax POST Request to Flask Application
Ajax POST Request to Flask Application

Time:03-31

I am trying to create a POST request from ajax using input type button. But the request is not sending

Need to send two separate request from each like below

html

            <input type="button"  name="hvalid" id="hvalid">
            <input type="button"  name="hinvalid" id="hinvalid">

ajax

$(function(){
    $('input').click(function(){
        var hvalid = $('#hvalid').val();
        var hinvalid = $('#hinvalid').val();
        $.ajax({
            url: '/pending_val',
            data : {'hvalid':hvalid,
                     'hinvalid':hinvalid},
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

Flask Route

@data_sources_api.route('/pending_val', methods=["GET", "POST"])
def pending_val():
        if request.method=='POST':
            print(request.form)

How hvalid and hinvalid request can be send separately

CodePudding user response:

html

 <input type="button"  name="hButton" id="hvalid">
  <input type="button"  name="hButton" id="hinvalid">

ajax

$(function(){
$('input[name="hButton"]').click(function(){
    $.ajax({
        url: '/pending_val',
        data : {'hvalidity': this.id },
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });
});

});

Flask

data_sources_api.route('/pending_val',methods=["GET", "POST"])
def pending_val():
    if request.method=='POST':
        print(request.form.get('hvalidity'))
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 
  • Related