Related dropout in flask, get data from sqlite database

I am trying to get html select tag with different counties (getting from database), when user selected county, I want another select tag to be included and show cities in that county (I have data in sqlite database where county id is in the city database). I am using python in Pycharm, with flask and I have not found any good tutorials.

Is there an easy way to use some flask extension? I've seen something about sijax, but I've never figured out how to use it.

The code I have is something like this, but I think the part of the city should be created with the javascript thingy:

        <div class="form-group">
            <label for="inputCounty">County</label>
            <select class="form-control" id="select_county" name="select_county">
                <option value="">Choose county</option>
                {% for county in counties %}
                    <option value="{{ county.id }}">{{ county.name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group">
            <label for="inputCity">City</label>
            <select class="form-control" id="select_city" name="select_city">
                <option value="">Choose city</option>
                {% for city in cities %}
                    <option value="{{ city.id }}" class="{{ city.county }}">{{ city.name }}</option>
                {% endfor %}
            </select>
        </div>

      

I tried the "chained" plugin -javascipt but it didn't work, but why do I have a class in option tags.

Counties and all cities are being sent to the html template right now, but I don't think it will be stable later because I want to add another dropdown with places in cities, so I have to send a lot of data that will never be used.

+3


source to share


1 answer


In yours, head

add a handler to change select values:

<script type="text/javascript">
    $("#select_county").change(function() {
        $.ajax({
            type: "POST",
            url: "{{ url_for('select_county') }}",
            data: {
                county: $("#select_county").val()
            },
            success: function(data) {
                $("#select_city").html(data);
            }
        });
    });
</script>

      

This uses jquery.change to determine when a county selection is selected and jquery.ajax to send that selected value to your server, which will look something like this:



@app.route('/select_county', methods=['POST'])
def select_county():
    ret = ''
    for entry in ...your_database_query...:
        ret += '<option value="{}">{}</option>'.format(entry)
    return ret

      

This list of tags is <option>

then inserted into the second select jquery.html .

+1


source







All Articles