POST communication Ajax for Flask

Asked

Viewed 1,209 times

3

I would like a help with a Python application using the Flask framework, I want to send and receive data via Javascript using Ajax, but I’m not sure how to do, all I got was a collection of different errors and no success.

main py.

from flask import request
from flask import json, jsonify
from flask import render_template as rt

app = Flask(__name__)

@app.route('/')
def index():
    usr = {
        'id': 1,
        'nome': 'bruno'
    }
    usr = json.dumps(usr)
    return rt('index.html', usr=usr)

@app.route('/usuario', methods=['GET', 'POST'])
def usuario():
    usr = {}
    if request.method == 'POST':
        if request.is_json:
            print('is_json:  {}'.format(request.is_json)) # retorna True
            usr = request.get_json(force=True)
            print('get_json: {}'.format(usr)) # retorna o JSON
            return jsonify(usr)
    #return rt('usuario.html', usr=usr)

if __name__ == '__main__':
    app.run(host='127.0.0.1')

index.html

<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello</title>
</head>
<body id="corpo" data-usr="{{ usr }}">
    <h1>Home</h1>
    <p>Ver <a href="{{ url_for('usuario') }}">usuário</a></p>
    <input type="button" onclick="alertar()" value="alerta">
    <input type="button" onclick="enviar_ajax()" value="enviar">

    <script src="{{ url_for('static', filename='jquery-3.4.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='main.js') }}"></script>
</body>
</html>

html user.

<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello</title>
</head>
<body id="corpo" data-usr="{{ usr }}">
    <h1>Usuário</h1>
    <p>Ver <a href="{{ url_for('index') }}">home</a></p>
    <p id="usr_id">{{ usr.id }}</p>
    <p id="usr_nome">{{ usr.nome }}</p>

    <script src="{{ url_for('static', filename='jquery-3.4.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='main.js') }}"></script>
</body>
</html>

main.js

function get_usr() {
    let usr = document.getElementById('corpo').getAttribute('data-usr');
    let usuario = JSON.parse(usr);
    return usuario;
}

function alertar() {
    let usuario = get_usr();
    alert(usuario.nome);
}

function enviar_ajax() {
    let usuario = get_usr();
    usuario.nome = 'Bruno';
    usuario.id = 42;
    const post_usuario = JSON.stringify(usuario);
    console.log('post_usuario: ' + post_usuario);

    $.ajax({
        url: '/usuario',
        type: 'POST',
        //data: JSON.stringify(usuario),
        //data: {'id': '7', 'nome': 'BRUNO'},
        data: post_usuario,
        //data: usuario,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        sucess: function (result, status, request) {
            console.log('Sucess');
            alert('Sucess');
        },
        error: function (event, jqxhr, settings, thrownError) {
            console.log('event: ' + JSON.stringify(event));
            console.log('jqxhr: ' + jqxhr);
            console.log('settings: ' + settings);
            console.log('thrownError: ' + thrownError);
            //alert('Error');
        }
    });
}

I happen to be able to send the data in the direction Python -> JavaScript, that is, the function alertar() receives the dice the way I would like, I believe there would be no problem in throwing them into some field of the HTML.

Now in the sense JavaScript -> Python is that there is some problem, I left commented on ajax all my attempts and that this one is the one that "works", I say in quotes, because I even receive the data in Python (see in print('get_json: {}'.format(usr))), but it does not go to the page usuario.

Another problem I noticed is that the ajax NEVER executes what is in the function sucess, tried to use done, but I had the same problem.

Error in current form (in browser):
post_usuario: {"id":42,"name":"Bruno"}
main.js:37 Event: {"readyState":4,"responseText":"<!DOCTYPE html>\n<html lang=\"pt-br\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <title>Hello</title>\n</head>\n<body id=\"corpo\" data-usr=\"{&#34;id&#34;: 42, &#34;nome&#34;: &#34;Bruno&#34;}\">\n <h1>Usuário</h1>\n <p>Ver <a href=\"/\">home</a></p>\n <p id=\"usr_id\"></p>\n <p id=\"usr_nome\"></p>\n\n <script src=\"/static/jquery-3.4.1.min.js\"></script>\n <script src=\"/static/main.js\"></script>\n</body>\n</html>","status":200,"statusText":"OK"}
main.js:38 jqxhr: parsererror
main.js:39 Settings: Syntaxerror: Unexpected token < in JSON at position 0
main.js:40 thrownError: Undefined

Notice that it returns status 200 OK, but with one mistake.

1 answer

1


The system was responding in the correct way, the reason for not performing the successful function is because it is misspelled, it should be success and not sucess.

It is important to note that the data should be sent using the stringify as follows:

data: JSON.stringify(data),

Let the backend do the recognition of this information and transform from string for JSON again.

Ajax should not redirect to another page, but fetch new data to the current page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.