What is the best way to pass the values of two interlinked drop-down menus through an AJAX post request to a Django view?

Presently, I am encountering an issue with sending the values of two dropdowns to a django view. My code would have functioned correctly if the dropdowns were independent. Unfortunately, this is not the case as the first one updates the second one. Therefore, I need to ensure that my AJAX post request happens once the second dropdown has been updated.

Below is my current HTML/Javascript code:

<select name="d1" class="toChange">
    {% for item in items1 %}
    <option val="{{ item }}"> {{ item }} </option>    
    {% endfor %}
</select>

<select name="d2">
    {% for item in items2 %}
    <option val="{{ item }}"> {{ item }} </option>    
    {% endfor %}
  </select>


<script type="text/javascript">
  function dropdownChange () {
    var value_d1 = $(".toChange option:selected").val();
    var value_d2 = $("select[name=d2] option:selected").val();
    $.ajax({
            url: '/myApp/templates/',
            type: 'POST',
            data: {'d1': value_d1, 'd2': value_d2},
            success: function(data) {
              var str = '';
              data.forEach(function(opt){
              str += '<option value="' + opt + '">' + opt + '</option>';
              });
              document.getElementById("d2").innerHTML = str;
            }
    });
    $(".toChange").change(dropdownChange);

The challenge here is that the change in d1 updates d2, but the AJAX call is made before d2 gets updated. This results in sending the wrong value to my view. How can I address this issue?

UPDATE: Integration of the suggested code by TM.96

 <select id="d1" name="d1" class="toChange">
    {% for item in items1 %}
    <option val="{{ item }}"> {{ item }} </option>    
    {% endfor %}
  </select>

  <select id="d2" name="d2">
    {% for item in items2 %}
    <option val="{{ item }}"> {{ item }} </option>    
    {% endfor %}
  </select>


<script type="text/javascript">

let select1 = document.getElementById('d1');
let select2 = document.getElementById('d2');

function onChangeSelect1() {

    window.select2.value = window.select1.options[window.select1.selectedIndex].value;

    onChangeSelect2();
}

function onChangeSelect2() {
    console.log('Value of Select 1: ' + window.select1.value);
    console.log('Value of Select 2: ' + window.select2.value);

    $.ajax({
            url: '/myApp/templates/',
            type: 'POST',
            data: {'d1': select1, 'd2': select2},
            success: function(data) {
              var str = '';
              data.forEach(function(opt){
              str += '<option value="' + opt + '">' + opt + '</option>';
              });
              document.getElementById("d2").innerHTML = str;
            }
    }); 
}
$(".toChange").change(dropdownChange);

</script>

UPDATE 2:

def MyView(request):

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


        result_r = request.POST.get('d1')
        result_d = request.POST.get('d2')
        query_results = data_immo.objects.all()
        regions = data_immo.objects.values_list("nom_reg", flat=True).distinct().order_by('nom_reg')
        departments = data_immo.objects.values_list("insee_dep").filter(Q(nom_reg=result_r)).distinct()
        cities = data_immo.objects.values_list("nom_com").filter(Q(insee_dep=result_d)).distinct()

        print(departments)

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

        departmentsVar=[]
        for item in departments:
            item = int(item[0])
            departmentsVar.append(item)

        departmentsVar.sort()
        departmentsVar = json.dumps(departmentsVar)

        citiesVar=[]
        for item in cities:
            citiesVar.append(item)

        citiesVar.sort()
        citiesVar = json.dumps(citiesVar)


        return HttpResponse(departmentsVar, content_type='application/json')

Technically, I need to return both departmentsVar and citiesVar but for some reasons my attempts have failed. It seems that I can only return one variable (so here departmentsVar). I tried to add the two in a dictionary but it didn't work.

Answer №1

Greetings, behold a simplified example I have crafted for your perusal:

On the Server side:

urls.py

urlpatterns = [
    path('Ajax/Test', views.ajax_test),
]

views.py

def ajax_test(request):
    return JsonResponse(request.GET)

On the Client side:

HTML

<label for="selectCity">City:</label>
<select id="selectCity" onchange="onChangeSelectCity()">
    <option disabled selected value> -- choose an option --</option>
    <option value="1">Dublin</option>
    <option value="2">New York</option>
</select>

<label for="selectState">State:</label>
<select id="selectState" onchange="onChangeSelectState()">
    <option disabled selected value> -- choose an option --</option>
    <option value="1">Ireland</option>
    <option value="2">USA</option>
</select>

<label for="selectCountry">Country:</label>
<select id="selectCountry" onchange="onChangeSelectCountry()">
    <option disabled selected value> -- choose an option --</option>
   <option value="1">Poland</option>
   <option value="2">Australia</option>
</select>

Javascript

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" 
    crossorigin="anonymous"></script>

<!-- JavaScript snippet -->
<script>
// Defining global variables, which can also be declared locally inside functions.
let selectCity = document.getElementById('selectCity');
let selectState = document.getElementById('selectState');
let selectCountry = document.getElementById('selectCountry');

// Triggered upon changing Select City.
function onChangeSelectCity() {
    // Output values of select fields in console.
    console.log('Upon change in Select City:');
    console.log('Value of Select City: ' + window.selectCity.value);
    console.log('Value of Select State: ' + window.selectState.value);
    console.log('Value of Select Country: ' + window.selectCountry.value);

    // Invoke function when Select State changes too.
    onChangeSelectState(window.selectCity.value);
}

// Triggered upon changing Select State.
function onChangeSelectState(value = 0) {
    // If called from onChangeSelectCity.
    if (value > 0) {
        window.selectState.value = value;
    }

    // Output values of select fields in console.
    console.log('Upon change in Select State:');
    console.log('Value of Select City: ' + window.selectCity.value);
    console.log('Value of Select State: ' + window.selectState.value);
    console.log('Value of Select Country: ' + window.selectCountry.value);

    // Call function that's invoked upon changing Select Country.
    onChangeSelectCountry(window.selectState.value);
}

// Triggered upon changing Select Country.
function onChangeSelectCountry(value = 0) {
    // If called from onChangeSelectState.
    if (value > 0) {
        window.selectCountry.value = value;
    }

    // Output values of select fields in console.
    console.log('Upon change in Select Country:');
    console.log('Value of Select City: ' + window.selectCity.value);
    console.log('Value of Select State: ' + window.selectState.value);
    console.log('Value of Select Country: ' + window.selectCountry.value);

    // Place your ajax code here...
    let url = 'Ajax/Test';

    $.ajax({
        type: "GET",
        data: {
            'city': window.selectCity.value,
            'state': window.selectState.value,
            'country': window.selectCountry.value
        },
        url: url,
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Explanation:

I've set up three select fields (City, State, and Country).

  1. When City is changed, State and Country update accordingly.
  2. When State is changed, only Country updates. City stays the same.
  3. When Country changes, there are no further updates to City and State.

The ajax call triggers on all these conditions and sends the appropriate values to the Django view. The returned values get printed correctly in the console.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly. document.getElementsByCla ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

Two ways to make a call, whether it be from the same URL or from

I have implemented two methods, namely method1() and method2(). These methods are part of two separate web APIs which are published on different URLs. I am able to call these methods using the following URLs: www.aaa.com/api/firstcontroller/method1 www.b ...

Slide in the Toggle Effect to Your Navigation Menu

Seeking help with enhancing my jQuery dropdown menu to include a slide down toggle effect similar to this example: http://jsfiddle.net/LaSsr/188/. Any assistance in applying this slide effect to the following JSfiddle would be greatly appreciated. Thank yo ...

Executing unique calculations on Kendo UI Grid Columns

For experienced users, this may seem simple, but as a newcomer, I'm struggling with a basic arithmetic task. I want to multiply one of the column values (DealValue) by 0.05 in my Kendo grid setup. Despite looking through the Kendo docs, I couldn' ...

jwplayer - track viewing time - monetize by the minute - trigger action based on duration

My goal is to track the time duration that someone watches a video, ideally by triggering an action every minute. I'm aiming to create a pay-per-minute system where a credit is withdrawn from the user for each minute they watch. If this setup isn&apo ...

What is the most effective way to enlarge an HTML table in the center?

Currently, I am dynamically generating an HTML table using a repeater. The table consists of four columns that I populate with company data. My goal is to enable users to click on a row and have another row appear below it, containing a Google map and addi ...

Navigating a vast code repository in Node.js

As I prepare to start a Node.js project with a sizable codebase, my aim is to keep my code isolated from the node_modules directory. I am keen on utilizing namespaces and organizing my code into folders for better management. However, it seems like I woul ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

Unable to retrieve element using jQuery because it is specified by its href attribute. This pertains to

I'm having trouble accessing the "a" element with its href attribute. Specifically, I want to add a class to any element that has an href value of "#one". Check out this jsFiddle example. Using jQuery: // The tabs functionality is working correctly ...

Utilizing jQuery for resizing images

I'm encountering an issue with my Jquery code as I work on creating a gallery feature. My goal is to have the selected image appear in the center of the screen when clicked, resized to fit the screen size if necessary. However, I've run into perf ...

The add-on for imageminJpegTran is designed to rotate images with ease

When I compress a buffer obtained from a file and rewrite it as a compressed version in memory, I am facing an issue where vertical images are being rotated while square and rectangle images are compressed correctly. Is there a way to pass options to the ...

Retrieving elements within an object using jQuery

Here's some code I'm working on: function popAreaTree() { var tree = $("ol.tree"); var list1 = tree.children('li'); var list2 = list1.children('ol').children('li'); $(tree).on(&apo ...

Efficiency levels of reach = within angular instructions

Creating a directive can be done in various ways. Here is an example of how I structured mine: 'use strict'; myApp.directive('mySwitchOnOff', [ '$rootScope', function($rootScope) { return { restrict: 'C' ...

In JavaScript, how is the symbol "." referred to as?

While I am familiar with its purpose and the language terminology, could you please provide the official name for the period/dot used in Javascript/jQuery? Appreciate your help! ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Displaying the second div once the first div has loaded, then concealing the first div

Current Approach: There are two divs occupying the same space, with div1 set to display:block and div2 set to display:none When a tab is clicked, jQuery hides one div over a period of 2000ms and reveals the other div. Challenge: The goal is for the ...

Drag and Drop File Upload plugin

I need a comprehensive example with code for the Really simple jQuery Ajax File Upload plugin. Unfortunately, the download links don't provide the complete code and example. Can someone please direct me to where I can find this information? ...

"Master the art of implementing a slide toggle effect with jQuery UI using

Looking to implement the jQuery UI slide toggle functionality in plain JavaScript... <center> <button id="button" class="myButton">Read More</button> </center> <div id="myDiv"> <p>Cool Read More Content Here. Lorem Ips ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...