Here is my jquery code
$(document).ready(function () {
    $('.bar_dropdown').on('change', function() {
        console.log("dropdown changed")
        $('#bar_graph_form_id').submit(function(event) {
            event.preventDefault();
            var data = new FormData($('#bar_graph_form').get(0));
            $.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: data,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log('form submitted successfully')
                    console.log(data)
                }
            })
        })
    })
})
Here is my HTML
<form id="bar_graph_form_id" method="post" action="display_bar_graph" name="bar_graph_form">
    {% csrf_token %}
    <select class="form-select bar_dropdown" aria-label="Default select example" name="bar_graph_dropdown">
        <option selected>Select data to visualise</option>
        <option value="1">By category</option>
        <option value="2">By language</option>
    </select>
</form>
<div class="bar_graph_container">
</div>
When the dropdown value changes, I want the form to submit and a django view triggered. This is my view
def display_bar_graph(request):
    if request.method == 'POST':
        user_select = request.POST['bar_graph_dropdown']
        if int(user_select) == 1:
            graph = open('./graphs/bar1.html', 'r').read()
        
        if int(user_select) == 2:
            graph = open('./graphs/bar2.html', 'r').read()
        
        context = {'html_data': graph}
        
        print('the form was submitted using ajax')
        return JsonResponse(context)
The idea is that a plotly graph be displayed in bar_graph_container div when the dropdown value changes.
But I notice that this code $('#bar_graph_form_id').submit(function(event) { does not work. I removed the function from the submit as follows $('#bar_graph_form_id').submit() and this works fine.
I wonder what I am doing wrong.
 
    