Re-populating Dropdown from Python to jQuery webpage

Issue

I am creating a movie recommendation program with Python/Flask but I have encountered an issue.

The function of the program is for a user to select a movie from a large dropdown and receive a recommendation using collaborative filtering. All of the logic works as intended but I will describe the issue below.

To summarize, the Python starts with a pandas dataframe that is converted to json. That json is sent through flask to the javascript/jquery function which populates an html dropdown.

Python:

@app.route('/', methods=['GET'])    
def index():
    final_data_pass = df.to_json(orient='records')
    return render_template("index.html", final_data_pass=final_data_pass)

HTML:

<form method="POST">
    <label>What is your favorite movie?</label>
    <select name="dropdown" id="sel"></select>
    <input type="submit" />
</form>

Javascript/jQuery

<script>
    $(function() {
        var data =  {{final_data_pass|safe}}
        $.each(data, function(i, option) {
        $('#sel').append($('<option>').attr("value", option.newId).text(option.title));
        });
    })
</script>

So, the dropdown menu successfully populates when the page loads, and a movie can be selected and submitted with the submit button to return the recommendation to the screen. The issue is that after the submit button is pressed, the dropdown is not re-populated.

I am aware that the script will only run once and leaves the webpage static, but I am lost as to coding out a solution to have the dropdown re-populate.

Let me know if there is anything else needed to understand the problem.

Thank you!

Update: I am attempting to use ajax as suggested by Bravo, but when I replace the script with:

$(document).ready(function () {
       $.ajax({
           type: "GET",
           url: "/",
           data: {{final_data_pass|safe}},
           success: function (data) {
               var s = '<option value="-1">Select a movie</option>';
               for (var i = 0; i < data.length; i++) {
                   s += '<option value="' + data[i].newId + '">' + data[i].title + '</option>';
               }
               $("#sel").html(s);
           }
       });
   });

The page gets slow and delayed, as well as the options saying "Undefined" instead of movie names.

Solution

Solution that worked in my situation is to add the Flask variable and definition to a POST method (in addition to being used in the GET method function).

@app.route('/', methods=['POST'])    
def submitted():
    ...
    ...
    ...
    final_data_pass = df.to_json(orient='records')
    return render_template("index.html", final_data_pass=final_data_pass)

Answered By – Brian S

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published