pythonjqueryajaxflaskpython-requests

How can I create a request and response with JQuery Ajax and Flask?


So I'm new to JQuery and using Flask, I've been trying to figure out how I can send data to my server and then send a response back successfully, however, everything I've tried and read up about doesn't seem to work.

In terms of what I want to do, I have a simple html form with some checkbox inputs. I'd like to send the form data on submit to the server, so I can manage it and then send back a response. I'm not too fussed about managing it right now, I just wanted to figure out why the connection between them isn't working. I'm getting no errors logged yet nothing seems to react (so assumingly, either my JS or Python are written incorrectly). I currently have a print line in my Python code to see if it reaches that point, but it appears not to.

I was wondering if there's anything specific I am doing wrong stopping the request from working as desired?

Here is the current attempt in my JS file:

$(document).ready(function(){

    $("#filterform").on("submit", function(e){
        e.preventDefault();

        var datastring = $(this).serialize(); 
        $.ajax({ 
            type: "GET",
            url: "/movies",
            data: datastring,
            dataType: "json", 

            success: function(response_data){
                console.log(response_data);
            },
            error: function() {
                console.log("request failed");
            }
        })
    });
});

to follow up, here's my app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route("/movies", methods = ["GET"])
def movies():
    print("test")
    return request.args()

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

A simplified version of my HTML & CSS for anyone who want's to replicate it:

<!DOCTYPE html>
<head>
    <title>Movie Selection</title>
    <link rel="stylesheet" href="../static/main_styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="scripts/main.js"></script>
</head>
<body>
    <div id="palette">
        <div class="palette_item" id="palette_item">BOX1</div>
        <div class="palette_item">BOX2</div>
        <div class="palette_item">BOX3</div>
        <div class="palette_item">BOX4</div>
    </div>
    <div id="detailrow">
        <form id="filterform" method="get">
            <div id="filtersrow">
                <div>
                    Action <input type="checkbox" class="filter" name="action">
                </div>
                <div>
                    Family <input type="checkbox" class="filter" name="family">
                </div>  
            </div>
            <div id="buttonrow">
                <input type="submit" value="Generate" id="submitbtn">
            </div>
        </form>
    </div>
</body>
</html>
#palette {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
    box-sizing: border-box;

    background-color: rgb(52, 148, 148);
}

.palette_item {
    flex-direction: column;
    flex-wrap: wrap;

    width:20%;

    text-align: center;
    background-color: white;
    border: 2px solid black;
}

#detailrow {
    display:flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}

#filtersrow {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    padding-top:5%;
}

#buttonrow {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;

    padding-top: 5%;
}

Solution

  • You can't use /movies as URL for the request, as long as you don't proxy the requests to your server.

    remove the "host" parameter in app.run() and send the ajax request to http://127.0.0.1:5000/movies instead of just /movies

    This should solve the problem.

    Edit:

    So there are two things you would wanna change. first of all in the js file

    $(document).ready(function(){
    
        $("#filterform").on("submit", function(e){
            e.preventDefault();
    
            var datastring = $(this).serialize(); 
            console.log(datastring)
            $.ajax({ 
                type: "GET",
                url: "http://127.0.0.1:5000/movies", // change the url to localhost
                data: datastring,
                dataType: "json",  // if you use json here, the response should be json too, otherwise jquery will try to convert 
                                   // the response to json and throw an error if it fails
    
                success: function(response_data){
                    console.log(response_data);
                },
                error : function(request,error)
                {
                alert("request failed");
                }
            })
        });
    });
    

    and in the .py file

    from flask import Flask, render_template, request
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app) # add cors so you don't get a cors error
    
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    
    @app.route("/movies", methods=["GET"])
    def movies():
        print("test")
        return {"message": "Hello World"} #you have to return json here as explained in the js file
    
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    It should log "Hello World" to the browser console