How to send data to Flask via AJAX?

12,333

Solution 1

new_freq = $('#input').val() //value I want to send 
$.ajax({ 
    url: '/set_freq', 
    type: 'POST', 
    data: new_freq,
    success: function(response){ 
        $('#main').text(response) 
    } 
})

in Flask

new_freq = request.get_data()

Solution 2

In the ajax code use a dictionary instead :

data: {
  'new_freq': new_freqd  //  to the GET parameters
},

in your app views, to retrieve it use :

new_freq = request.args.get('new_freq')
Share:
12,333
Bohdan
Author by

Bohdan

BY DAY: Student, studying Python BY NIGHT: Sleeper

Updated on June 17, 2022

Comments

  • Bohdan
    Bohdan almost 2 years

    I'm making small web project based on Flask. And I have to send some data to Flask, but I don't know how to do it. I tried different ways, tried to use JSON, but I don't know how to work with it. Maybe someone can share working piece of code with me or help by explaining what I have to do?

    new_freq = $('#input').val() //value I want to send 
    $.ajax({ 
        url: '/set_freq', 
        type: 'POST', 
        data: ,
        success: function(response){ 
            $('#main').text(response) 
        } 
    })
    
  • Bohdan
    Bohdan over 7 years
    Thanks! It works, but also I have to decode data from bytes after I accepted it
  • Simon J. Liu
    Simon J. Liu over 7 years
    Flask has many different methods to get the post value. use request.get_data() to get raw value. use request.args() to get params in url like xxx.com/xxx?a=1, use request.form() to get the data post in form. It depends on how you send the data to flask.