skip to Main Content

I have a problem when trying to update my dropdown (<select> element) based on Django model triggered by another dropdown (let’s call it A) change.

I followed this tutorial:
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

When I change the dropdown A, I get the following error:

Uncaught TypeError: $.ajax is not a function

Based on similar questions I made sure that I include this line before my script:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

and I’m not using the slim version of jquery.

Here is the part of my HTML code of my dropdown A and JS that is responsible for updating the second dropdown.

<select id="my-selection" dropdown-data-url="{% url 'ajax_get_data' %}">
   <option value="1">First Option</option>
   <option value="2">Second Option</option>
</select>


<script>
$(document).ready(function() {
    $("#my-selection").change(function () {

        var url = $("#my-selection").attr("dropdown-data-url");  // get the url of the proper view
        var my_selection = $(this).val();                        // get the selected input from dropdown
        $.ajax({                       
        url: url,                    
        data: {
          'selection': my_selection                              // add selected option to the GET parameters
        },
        success: function (data) {   
          $("#second-dropdown-selection").html(data);  
        }
        });
    });
});
</script>

I will be grateful for any suggestions.

2

Answers


  1. Chosen as BEST ANSWER

    It turned out that I had another jQuery version in my project (3.2.1 slim), however I didn't import it anywhere, probably some Django libraries had reference to it but I couldn't find it.

    To solve this I used to point to my jQuery 3.6.0 (normal version).

    <script type="text/javascript"> $360 = jQuery.noConflict();</script>
    

    Then I use $360 in ajax instead of $ to point use this specific jQuery version.


  2. May be you missed the type (GET/POST) in the ajax call

    $.ajax({                       
        url: url, 
        type:'get', //add this                  
        data: {
          'selection': my_selection 
        },
        success: function (data) {   
          $("#second-dropdown-selection").html(data);  
        }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search