Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
Showing POST http://localhost:81/test 404 (Not Found) when using JQuery,ajax

I am trying to pass javascript variables to python as a directory using the JQuery.ajax and flask application.

index.html

<body>
<label for="fname">First name:</label> <input type="text" id="fname" name="fname">
<label for="lname">Last name:</label><input type="text" id="lname" name="lname">
<button type="submit" onclick='myfunction();'>Click Here to pass your data</button>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
    function myfunction() {
        const firstname = document.getElementById("fname").value;
        const lastname = document.getElementById("lname").value;

        const dict_values = {firstname, lastname} 
        const s = JSON.stringify(dict_values); 
        console.log(s); 
        $.ajax({
            url:"/test",
            type:"POST",
            contentType: "application/json",
            data: JSON.stringify(s)});
}
</script>
</body>

app.py

import json
from flask import request
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')
@app.route('/test', methods=['POST'])
def test():
    output = request.get_json()
    print(output)
    print(type(output))
    result = json.loads(output)
    print(result)
    print(type(result))
    return result
if __name__ == '__main__':
      app.run(debug=True, host='localhost', port=81)

For now, I am just trying to print the dictionary in python output

In console,JSON string looks like this : {"firstname":"c","lastname":"c"}

But I get this error right after: POST http://localhost:81/test 404 (Not Found)

I am very new to this, I think there is something wrong with the URL path in ajax.

Files path are as follows:
index.html => localhost/index.html
app.py => localhost/venv/scripts/app.py

How can I solve this issue?
Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I assume that the form data, despite the transfer via AJAX, is also sent to the server as a GET request.

The following example shows you how to send the data to the server with jQuery.
If the form sends a submit event, the default behavior is suppressed with preventDefault. This means that the actual form is no longer sent.
Then all data of the form are requested and converted into an object. Before sending the POST request using AJAX, this object is converted into JSON format.
The server receives the data and returns it.

HTML (templates/index.html)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <form name="my-form">
      <div>
        <label for="fname">First name:</label>
        <input type="text" id="fname" name="firstname">
      </div>
      <div>
        <label for="lname">Last name:</label>
        <input type="text" id="lname" name="lastname">
      </div>
      <button type="submit">Click Here to pass your data</button>
    </form>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script>
      (function(uri) {
        
        // Wait for the complete document.
        $(document).ready(function() {
          // Register a listener for the submit event.
          $('form[name="my-form"]').submit(function(evt) {
            // Suppress the default behavior of the form.
            evt.preventDefault();

            // Extract the form data and convert it to an object.
            const data = {};
            $.each($(this).serializeArray(), function(i, item) {
              data[item['name']] = item['value'];
            });

            // Send the data to the server.
            $.ajax({
              url: uri,
              type: 'POST',
              contentType: 'application/json',
              dataType: 'json',
              data: JSON.stringify(data)
            }).done(function(data) {
              // Receive the reply.
              console.log(data);
            })
          });
        });

      })({{ url_for('test') | tojson }});
    </script>
  </body>
</html>
Flask (app.py)
from flask import (
    Flask,
    jsonify,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/test', methods=['POST'])
def test():
    data = request.json
    print(data)
    return jsonify(data)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda