0

I have a feeling this is pretty basic stuff, it sounds like it should be. But I can't find this anywhere online. The setting is simple: I have a variable foo = 1, now all I want to do is send that over to my app.py. I understand that I would be needing AJAX, so I have that in there as well. Curently what I think I need to do is something like this:

js :

$(function() {
        $('#btn').click(function() {
            var answer = 1
        $.ajax({
            url: '/checkAnswer',
            data: answer,
            type: 'GET',
            success: function(data) {
                console.log(data);
            },
            error: function(error) {
                console.log(error);
            }
        });
        });
        });

py :

@app.route('/checkAnswer', methods=['GET', 'POST'])
def checkAnswer():
    try:
        answer = request.data
        if answer == 1:
            return 'ham'
        else:
            return answer

    except Exception as e:
        return 'foo bar'
Thom Ernst
  • 379
  • 1
  • 4
  • 15

1 Answers1

1

It would be better to use POST instead of GET as you're transmitting data. Also the done and fail promises are typically more clear and more useful that callbacks.

js :

$(function() {
    $('#btn').click(function() {
        var answer = 1
        $.ajax({
            url: '/checkAnswer',
            data: {
                answer: answer
            },
            type: 'POST'
        }).done(function(data) {
            console.log(data);
        }).fail(function(error) {
            console.log(error);
    });
});

py :

@app.route('/checkAnswer', methods=['POST'])
def checkAnswer():
    try:
        answer = request.form['answer'] if 'answer' in request.form else None
        if answer == 1:
            return 'ham'
        else:
            return answer

    except Exception as e:
        return 'foo bar'

The line request.form['answer'] is best case. However, in the past when posting data with ajax, I've had to do this to get the data:

answer = request.form.getlist('answer')[0]

Because of this, I would suggest sending JSON:

js:

$(function() {
    $('#btn').click(function() {
        var answer = 1
        $.ajax({
            url: '/checkAnswer',
            data: JSON.stringify({'answer': answer}),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        }).done(function(data) {
            console.log(data);
        }).fail(function(error) {
            console.log(error);
    });
});

py:

@app.route('/checkAnswer', methods=['POST'])
def checkAnswer():
    data = request.get_json()
    if data is None:
        return 'foo bar'
    answer = data['answer'] if 'answer' in data else None
    if answer == 1:
        return 'ham'
    else:
        return answer

Note: Setting the content type in the ajax request is important, as if it is not set, request.get_json() returns None.

Allie Fitter
  • 1,689
  • 14
  • 18