Refresh the dropdown menu options using Dojo's AJAX capabilities

Hi there, I'm currently using the code below to create a cascading dropdown menu. In this code, I have a function called xyz() which makes an AJAX call to a servlet and sets the result in a variable separated by commas. Then, I split the result by comma and store it into the second dropdown. The issue I'm facing is that when I change the value in the first dropdown, the second dropdown is not populated even though the AJAX call is made. And when I change the value for the second time, the second dropdown populates with the wrong value that was selected previously. Can you please help me identify what's causing this problem?

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" href="js/dojo/dijit/themes/claro/document.css"/>
    <link rel="stylesheet" href="js/dojo/dijit/themes/claro/claro.css" />
    <script src='js/dojo/dojo/dojo.js' data-dojo-config=' parseOnLoad: true'></script>
    <script>
        dojo.require("dijit.form.ComboBox");
        dojo.require("dojo.data.ItemFileReadStore");
        dojo.require("dojo.ready");
        dojo.require("dojo.store.Memory");
        require(["dojo/parser", "dijit/form/ComboBox","dijit/form/TextBox","dojo/dom-construct"]);
     function xyz(){
      dojo.xhrPost({
            // The URL to request
            url: "populate",
            timeout :  3000 ,
            content: {
                username: document.getElementById("state").value

            },

            load: function(result) {                
         require(["dijit/form/ComboBox", "dojo/ready","dojo/store/Memory"], 
                function(ComboBox,ready,Memory){

                    ready(function() {

                        dojo.connect(dijit.byId('state'), 'onChange', function() {

                            var stateSelect = dijit.byId('stateSelect');

                            if (!stateSelect) {
                                stateSelect = new ComboBox({id: "stateSelect",name:"select",value: "Select",searchAttr:"name"},"stateSelect");

                            }

                            var str_array = result.split(',');

                            var data = [];
                            dojo.forEach(str_array, function(item, idx) {
                                data.push({
                                    id: idx,
                                    name: item                    
                                });
                                stateSelect.set('store', new Memory({data: data}));


                            });


                        }); // dojo.connect



                    }); // ready   



                }); // require  

        }



      });

    }


    </script>
</head>
<body class="claro">

    <select data-dojo-type="dijit.form.ComboBox" id="state" name="state" onchange="xyz()"  >

        <option selected>Andaman Nicobar</option>
        <option>Andhra Pradesh</option>
        <option>Arunachal Pradesh</option>


    </select>

    <select data-dojo-type="dijit.form.ComboBox" id="stateSelect" name="stateSelect">

    </select>


</body>

Answer №1

On the second attempt, stateSelect is populated because of the use of dojo.connect, which binds an onChange event to the state and triggers a callback to populate stateSelect.

It is recommended to remove dojo.connect as it is not necessary in this case.

To retrieve the correct value, consider using dijit registry like this:

registry.byId("state").get("value")
instead of
document.getElementById("state").value

Consider using FilteringSelect for better functionality. Learn about the differences between Combobox and FilteringSelect here

Additional tips:

Use dojo.request module instead of xhrPost

Instead of using onchange=xyz(), add an event handler when the DOM is ready with your function as the callback.

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

The deepToString function found in the Arrays class

I found myself wondering about the functionality of deepToString and decided to take a closer look at the method. One thing that puzzled me was the purpose of multiplying 20 by the length of the array object. Can you explain what this accomplishes? pub ...

The PhoneGap Camera is throwing an error: "Undefined property 'getPicture'."

My current challenge involves integrating the Camera API into my PhoneGap android app. However, I keep encountering an error that reads "Cannot read property 'getPicture' of undefined". I have extensively searched through StackOverflow answe ...

Image flipping effect malfunctioning in Safari and Internet Explorer

My image flipping effect is not functioning properly in Safari and IE browsers. Here is the code I am using: .flipcard { position: relative; width: 220px; height: 220px; perspective: 500px; margin: auto; text-align: center; } .flipcard.v:hove ...

I'm currently facing difficulties transferring data as I'm unable to pinpoint the error in my jQuery Ajax code

I am currently working on my index page and I have a requirement to submit form data without reloading the page. To achieve this, I want to utilize AJAX with jQuery for a seamless user experience. Could you provide feedback on my implementation using jQue ...

Is it possible to access a comprehensive list of URLs required to download packages from the node modules?

After cloning a project and running npm install, I am interested in obtaining a comprehensive list of all the URLs used to download the files. Is there a method to retrieve this list? ...

Navigating with the keys is disabled until an item is chosen

Currently working on a Shopify website for a client and encountered an issue where the keys don't scroll down upon page load unless a specific element is clicked or tab is used. I am not sure what caused this unexpected behavior, it may have occurred ...

NextJS was throwing a warning at me, while Firebase hosting was giving me an error regarding the absence of unique keys for children in lists, even though I

I've been troubleshooting this warning for quite some time, but I can't seem to resolve it. The warning reads as follows: Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using <ul>. ...

Utilizing Express and ejs to display a JSON using the "<%" tag

I am facing an issue with the code in my index.ejs file. The current code snippet is as follows: var current_user = <%= user %> In my node.js file, I have the following code: app.get("/", function(req, res){ res.locals.user = req.user res. ...

How to troubleshoot WordPress Ajax function not getting form data

I am currently working on a form in my plugin where I need to send data to my AJAX action function using the standard WP Ajax techniques. Here is the basic structure of my form: <form role="form" id="signup_widget_form" method="post" action="#"> ...

Refreshing the page in Next.js causes issues with the CSS classNames

I am currently in the process of migrating a React SPA to Next.js, and I am relatively new to this framework. The issue I am encountering is that when I initially load the Home page, everything appears as expected. However, if I refresh the page, incorrect ...

Encountering an Issue with jQuery 1.9.1 when Checking the #idCheckbox in Internet Explorer Versions 7 and 8

Currently, I am utilizing jQuery version 1.9.1 and my code is functioning smoothly on IE9, Firefox, and Chrome. However, the issue arises when trying to make it work on IE7 and IE8, where it fails to execute. In my setup, there is an input checkbox with t ...

Unable to access custom login page for Spring Security due to login malfunction

I've encountered an issue where the custom login page doesn't seem to be functioning correctly. Instead of redirecting me to the index page, it directs me to the login?error URL. Interestingly, when utilizing the default Spring Security page, eve ...

The LocalSessionFactoryBean is unable to scan multiple packages specified in the packagesToScan property

Currently, I am delving into the realms of Hibernate and Spring, juggling multiple entity classes. Here is the directory structure of my project: https://i.sstatic.net/xOcry.png In this scenario, both LoginUser and Student are designated as entities annot ...

Interpreting XML in Java using a WSIL document

Currently, I am working on creating a program that can extract a link from an XML file using Jsoup. Below is my current code: public static String XmlReader() { InputStream is = RestService.getInstance().getWsilFile(); try { Document doc ...

"Attempting to troubleshoot a calculator built with html, css, and js. I'm stumped as to what could

After following a tutorial on YouTube, going over the code multiple times, and still experiencing issues with the calculator. Sometimes it works fine, other times certain buttons like (+, -, x, ⁄) don't function properly. I've provided the enti ...

Tips for invoking a .aspx document within a .ascx file using json and ajax technology

Currently in the process of developing a large website using ASP.net and either vb.net or C#, I am facing a challenge where upon clicking a button, specific text should be displayed on the site. To achieve this, I plan to utilize ajax/json to call a .aspx ...

Delay fading in during the loading process

Recently, I came across a neat animation effect that I would love to incorporate into an upcoming project. The effect involves animating the opacity on load, also known as a fade in. I am curious if it is possible to link multiple elements together (for ...

Slow CSS :hover animations in the most recent release of Chrome

I recently upgraded my browser from chromium version 67 to the latest Chrome version 79. However, I noticed that after the upgrade, the CSS transitions on my website have become very laggy and unresponsive. Surprisingly, everything works perfectly fine on ...

Efficient communication across angular modules on a global scale

Currently, I am working on a project that involves Angular2 with multiple modules. One of the main modules is called BaseModule, and in addition to that, there are two extra modules - FirstModule and SecondModule. Each module has its own routing mechanis ...

maven Do not utilize the term ${name} anymore as it is no longer in use. Instead, please use ${

Struggling to pinpoint the origin of this error message and its fix, unfortunately unable to share the pom file as it contains company-sensitive information The expression ${name} is outdated. Switch to ${project.name} instead. It's crucial to addres ...