Home > Software engineering >  Trouble with AJAX POST request in Flask web application
Trouble with AJAX POST request in Flask web application

Time:11-05

I'm working on a web application using Flask and I'm having trouble with an AJAX POST request. I am working of a signup page. When I click the submit button on my form, nothing is happening, and there are no XHR entries in the network tab of the browser's developer tools as well as no console entries. I've double-checked my code, but I'm unable to identify the issue. Can someone please help me troubleshoot this problem?

Please find below the relevant parts of my code:

#app.py

from flask import Flask, render_template, request

app = Flask(__name__)

from user import routes

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'GET':
        return render_template("login/home.html")
    else:
        print("do not know")

# @app.route('/dashboard/')
# def dashboard():
#     return render_template("login/dashboard.html")

if __name__ == "__main__":
    app.run(debug=True)

Created users folder for managing the model classes and there routes

#user/models.py
from flask import Flask, jsonify

class User:
    def signup(self):
        user ={
            "_id":"",
            "name":"",
            "email":"",
            "password":""
        }
        return jsonify(user), 200

\#user/routes.py

from flask import Flask
from __main__ import app
from user.models import User

@app.route('/user/signup', methods=\['POST'\])
def signup():
user = User()
return user.signup()

The view or HTML code

base.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/scripts.js"></script>
  </head>
  <body>
    {% block login_content %}
        
    {% endblock login_content %}
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
  </body>
</html>

home.html

{% extends 'login/base.html' %}
{% block login_content %}

<div >
    <div >
        <div >
            Featured
        </div>
        <div >
            <form  id = "signup_form" name="signup_form">
                <div >
                    <label for="register_name" >Name</label>
                    <input type="text"  id="register_name" name="register_name">
                </div>
                <div >
                    <label for="register_email" >Email address</label>
                    <input type="email"  id="register_email" name="register_email">
                </div>
                <div >
                    <label for="register_password" >Password</label>
                    <input type="password"  id="register_password" name="register_password">
                </div>
                <!-- <div >
                    <input type="checkbox"  id="exampleCheck1">
                    <label  for="exampleCheck1">Check me out</label>
                </div> -->
                <button type="submit" id="submit_signup_form" >Sign Up</button>
            </form>
        </div>
    </div>
</div>
{% endblock login_content %}

script.js

$("#signup_form").submit(function(e) {

    var $form = $(this);
    var $error = $form.find(".error");
    var data = $form.serialize();
  
    $.ajax({
      url: "/user/signup",
      type: "POST",
      data: data,
      dataType: "json",
      success: function(resp) {
        // window.location.href = "/dashboard/";
        console.log(resp)
      },
      error: function(resp) {
        // $error.text(resp.responseJSON.error).removeClass("error--hidden");
        console.log(resp)
      }
    });
  
    e.preventDefault();
  });

What I've Checked:

  • I've verified that jQuery is included and the paths to JavaScript files are correct.

  • My server is running and accessible at the specified URL.

  • The Flask route seems to be correctly configured, but I'm not getting the expected response in the browser.

  • Also changed between form id and form name

I would greatly appreciate any guidance or insights you can provide to help me resolve this issue. Thank you in advance!

CodePudding user response:

The button id is submit_signup_form

<button type="submit" id="submit_signup_form" >Sign Up</button>

but in the script you have signup_form

$("#signup_form").submit(function(e) {

Try to change the id of the button to <button type="submit" id="signup_form" ...

  • Related