Populate a select list in real time with dynamically generated options

I'm facing a challenge at the moment; I am using JavaScript to dynamically generate select boxes, however, I require Ajax to populate them with options. At the moment, my code is returning undefined and I am unsure of how to proceed. While my PHP successfully returns the information, the JavaScript seems to be having trouble parsing it. Any additional help or insight would be greatly appreciated;

function getSkilllist(group) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
    xmlhttp.send();
}

function addInput(divName,group) {
var skillst = getSkilllist(group);
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="ski[]">' + skillst + '</select> .....

The rest of the function works as intended, but the issue lies in the var skillst variable returning undefined, and the reason behind this eludes me. It could possibly be related to strings, yet I am struggling to identify the solution.

Answer №1

Your current function lacks a return statement, causing it to malfunction. Consider using the following revised code:

function fetchSkillList(group) {
if (window.XMLHttpRequest) {// for modern browsers
    xmlhttp=new XMLHttpRequest();
}
else {// for older versions of Internet Explorer
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
       var newDiv = document.createElement('div');
       newDiv.innerHTML = '<select name="skills[]">' + xmlhttp.responseText + '</select> ....

       // insert in DOM here
    }
}
xmlhttp.open("GET","generate_skill_list.php?group=" + group + "&t=" + Math.random(),true);
xmlhttp.send();
}

function createInput(divName, group) {
fetchSkillList(group);

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

Angular and JavaScript Performing Slide-Up Animation

Currently, I am working on creating a menu using Angular and JavaScript. My goal is to have this menu toggle between showing and hiding when a button is clicked. If you would like to view the code that I have written so far, you can check out the demo her ...

I recently installed bootstrap, jquery, and popper.js on my live server, but to my surprise, nothing was appearing on the screen. Despite compiling the

After successfully installing bootstrap, jquery, and popper.js, I encountered an issue on my live server where nothing was displaying. Oddly enough, no errors were detected after compiling the code. import { createApp } from 'vue' import App from ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

What is the best method to retrieve a nested JSON property that is deeply embedded within

I am facing an issue with storing a HEX color code obtained from an API in a Vue.js app. The object app stores the color code, for example: const app = {"theme":"{\"color\":\"#186DFFF0\"}"}. However, when I try to access the color prope ...

Utilize custom SMTP with JavaScript to dispatch emails

I'm wondering if it is possible to send emails using just JavaScript (I am working on a PhoneGap app). I envision a scenario where I can connect to a specific SMTP server with a login and password, and then send emails using that connection. I have al ...

Do I need to use the "--save" flag in npm to add dependencies to the "package.json" file?

Do I really need to use the "--save" flag in order to add an installed dependency to the "package.json" file? I conducted a test without the "save" flag and found that the package was still added to the "dependencies" section. It seems like it is the defa ...

When running `npm install`, it attempts to install version 1.20.0 of grpc even though version 1.24.2 is specified in

After running npm install on my React-Native project, an error occurred stating that it was attempting to install gRPC version 1.20.0, but my package.json and package-lock.json specified gRPC version 1.24.1. I attempted to fix the issue by adjusting the v ...

The concept of CSS sprites and managing background positions

I have been working on integrating a star-rating widget that requires the use of a sprite file. The sprite file I am using looks like this: https://i.stack.imgur.com/ZSMMj.png This is how my HTML is structured: HTML <span id="star-ratings" class="c ...

Datatables fails to execute page transitions

It seems like I must be missing something, even though my code is quite basic and closely follows the example provided on the web. I am currently using server-side paging. The issue I'm facing is that upon initial page load, the data from the server ...

No definition found for state

Currently, I am facing an issue while trying to fetch data from an API, set it on my State, and display that state in a table. The problem arises because the render method is called first, causing my state to be undefined which leads to this specific issue ...

Is it possible to utilize both the /app and /pages folders in my Next 13 application?

I am currently working on a project where the /app folder is utilized as the primary route container. However, we have encountered performance issues on localhost caused by memory leaks identified in an issue on the Next.js repository. I am curious to fi ...

jQuery function to automatically close any other opened divs when a new div is opened

I have multiple elements that reveal a div when clicked. The issue is that if all elements are clicked, all divs open instead of just the one that was clicked. This is my jQuery code: <script> $(document).ready(function() { $('.servicemark ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...

What is the best way to include bootstrap using webpack?

I am currently building a webapp using Typescript and webpack. I have been able to successfully import some modules by including them in my webpack.config.js file as shown below. However, no matter how many times I attempt it, I cannot seem to import the b ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...

The LatinSquare.js script has exceeded the maximum call stack size limit

In my current project, I am utilizing the latin-square library for node.js within a loop to search for a specific pattern. However, I encountered an error after running the script for 2 minutes: RangeError: Maximum call stack size exceeded var latin ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...