-1

In my javascript I have some information that I want to send to my flask code and return after some code has run.

In javascript I have the following code:

    request.open('POST', '/update_price');
    const data = new FormData();
    data.append('sort', pizza);
    data.append('toppings', amount)
    request.send(data);

and flask:

@app.route('/update_price', methods=['POST'])
def update_price():

    sort = request.form.get("sort")
    toppings = request.form.get("toppings")

    // run some code

    return sort, toppings

How can I return sort and toppings to javascript? And do I send the data right in the first place?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Tijmen
  • 11
  • 4

2 Answers2

0

If the request object wasn't created, it should be created.

JavaScript:

const data = new FormData();
data.append('sort', pizza);
data.append('toppings', amount)

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log( this.responseText );
    }
};
request.open('POST', '/update_price');
request.send(data);

If you want to return variables from the server-side (flask), you can return your variables as a formatted string.

return '{} {}'.format(sort, toppings)
0

You don't return variables like that from a route function. Ideally you need to return a render_template() function, and pass the variables along with it, in this case to be rendered in the Javascript portion of the template you specify.

@app.route('/update_price', methods=['POST'])
def update_price():
    sort = request.form.get("sort")
    toppings = request.form.get("toppings")
    // run some code
    return render_template('template.html', sort=sort, toppings=toppings)

and in your template.html file, include the following:

<script type="text/javascript">
var sort= "{{ sort }}";
var toppings= "{{ toppings }}";
// Javascript function referencing the above two variables
</script>
CodeMantle
  • 1,249
  • 2
  • 16
  • 25