0

I have a Django project where I'm trying to run a JS/AJAX script when a dropdown changes value. The same code works well for a button, but not for the dropdown.

Here is the html code with the button, the dropdown and finally the script:

  <button class="toChange">AJAX POST TEST</button>

  <select class="toChange">
    {% for item in regions %}
    <option val="{{ item }}" {% ifequal item reg %} selected {% endifequal %}> {{ item }} </option>    
    {% endfor %}
  </select>

  <script type="text/javascript">
       $(".toChange").click(function(){
        $.ajax({
            type: 'POST', 
        }); 
    });

EDIT1: adding views.py and amending my dropdown to reflect it properly as I might have oversimplified my example.

def MyView(request):
    result_r = request.POST.get('reg')

    if request.method == 'POST' and request.is_ajax:

        result_r = request.POST.get('reg')
        query_results = data_immo.objects.all()
        regions = data_immo.objects.values_list("nom_reg", flat=True).distinct().order_by('nom_reg')
        departements = data_immo.objects.values_list("insee_dep").filter(Q(nom_reg=result_r)).distinct()

        query_results_dict = {
        'query_results': query_results,
        'regions': regions,
        'departements': departements,
        'reg': result_r
        }

        return render(request,'home.html', query_results_dict)

Why would it work with the button and not the dropdown? I'm really new to this, so do idea what is wrong. Thanks!

2
  • Listen for change on dropdowns, not click. Also, your AJAX request has no URL set. Commented Mar 6, 2020 at 17:39
  • I tried but didn't do anything. What shall I use as a URL? The URL of my html page? Commented Mar 6, 2020 at 17:49

1 Answer 1

4

You need to use the change event in case of <select>

$(".toChange").on('change', function(){ ... })
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately it didn't work. Any idea what is missing?
Post your complete code to know what might be wrong. What is meant by 'didn't work'?
Just posted more stuff. Please let me know if you need more info.
My bad, in fact my button was not triggering the AJAX code, but the standard POST request, hence the behaviour difference. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.