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

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

An AJAX response encountered a JSON parsing error along with an HTML comment

Reviewing the attached image reveals data returned from an ajax call to a PHP script. The array displayed is formed by the script, but for unknown reasons, it includes an HTML comment before the array. <!-- translation function --> The origin and ...

JavaScript Event Listener causing the Sticky Position to Break

I am currently dealing with a situation where I want to create a slide-in side menu that remains sticky. However, when I apply the position: sticky CSS property to my menu container, it causes the entire menu to be displayed (instead of being pushed off th ...

Learn how to dynamically populate a select2 dropdown with values retrieved from a database using JavaScript or jQuery

I am currently working on an edit form where I need to retrieve data from a MySql database using Ajax. The form includes two select2 dropdowns and I want the fetched data to be displayed inside those dropdowns. For example: Let's say I have created a ...

Firebug reveals the JSON data being sent through AJAX requests, whereas PHP indicates that the $_POST variable is empty

I am currently working on my first AJAX transaction and, unfortunately, I have hit a roadblock towards the end. I am attempting to send a JSON string via AJAX to a php page called verify.php. However, when I try to retrieve this data, it appears that $_P ...

Identifying asynchronous JavaScript and XML (AJAX) requests using Express in NodeJS

When working with NodeJS and Express, I am wondering how to distinguish between a regular browser request and an AJAX request. I understand that one approach is to inspect the request headers, but I am curious if Node/Express provides direct access to th ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

Karma Test Requirement: make sure to incorporate either "BrowserAnimationsModule" or "NoopAnimationsModule" when using the synthetic property @transitionMessages within your application

TEST FILE import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform- browser/animations'; import { ManagePageComponent } from './manage-page.component& ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Utilizing ActionScript 2 to Access WCF Service

I am collaborating with a Flash designer on a project as a.NET programmer. Our plan involves the designer creating a flash-based UI (utilizing AS2) for a questionnaire presentation. Once an end user completes the questionnaire, they will send the answers t ...

Phonegap fails to make a successful login Ajax call to Yii

Currently working on my initial phonegap application and facing a login issue. I have an appLogin action in the site controller which successfully logs in if the credentials get validated. However, the ajax call in the app fails to retrieve a response. If ...

Execute two tasks simultaneously in two separate workers utilizing the cluster module in node.js

I'm currently diving into clustering with NodeJS. My goal is to have two separate tasks - one handling node-sass and the other managing uglifyjs - each running on a distinct worker using cluster in NodeJS. The code I've implemented seems to be fu ...

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

Guide on validating an Australian phone number with the HTML pattern

When it comes to PHP, I have found it quite simple to validate Australian phone numbers from input using PHP Regex. Here is the regex pattern I am currently using: /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ | ...

What sets apart importing components in computed from importing components in dynamic import in Vue.js?

Imagine there are 4 components available on a page or within a component, and the user can utilize them based on their selection by toggling between Input, Image, Video, or Vudio components. There are two ways to lazily load these components: 1) <temp ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...