developing a dropdown menu in JavaScript using data from a text document

Is it possible to achieve this task? If so, any assistance would be greatly appreciated. I am relatively new to JavaScript and have limited knowledge of syntax rules and best practices.

I've created some functions in an external file.

var myFunctions = myFunctions || {};

myFunctions.requestAjax = function () {

    try{

        return new XMLHttpRequest();

    } catch (e) {

        try {

            return new ActiveXObject("Msxml2.XMLHTTP");

        } catch (e) {

            try {

                return new ActiveXObject("Microsoft.XMLHTTP");

            } catch (e) {

                alert("Your browser seems to have an issue! Please ensure that JavaScript functionality is enabled.");
                return false;
            }
        }
      }
}

myFunctions.onReadyStateChange = function(ajaxRequest, formName, formArray, method, controller) {

    var verifiedMethod = validateMethod(method);

    if (!verifiedMethod) {
        throw new Error("Error: Please make sure the method passed matches 'GET' or 'POST'.");
    } 

    for (input in formArray) {
        document.formName.input.value = ajaxRequest.responseText;
    }

    ajaxRequest.open(method, controller, true);
    ajaxRequest.send(null);
}


myFunctions.writeDropDownList = function(textFile, method, path) {

    var file = myFunctions.requestAjax();

    file.open(method, path, true);

    if (file.readyState != 4) {
        throw new Error("Error: Text file ready state is not equal to 4!");
    }

    if (file.status != 200) {
        throw new Error("Error: Text file status is not equal to 200!");
    }

    var lines = file.responseText.split("\n");

    document.writeln("<select>");

        for(line in lines) {
        document.writeln("<option>" + line + "</option>");
    }

    document.writeln("</select>");

    file.send(null);    
}

myFunctions.validateMethod = function(method) {

    var lowerCaseMethod = method.toString().toLowerCase();

    switch(lowerCaseMethod) {
        case "get":
        case "post":
            return true;

        default:
            return false;
    }
}

The HTML code trying to implement the functions

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="../includes/css/adsmanager.css" />
        <script type="text/javascript" src="../includes/js/myFunctions.js"></script>
    </head>
    <body>

        <form name='adsManager'>
            <button type="text" value="test" onclick="createCountriesList()">Click to create countries list</button>
        </form>

    </body>
</html>

I intend to use these functions for various purposes, hence the decision to create a namespace. I came across this resource which served as a reference for most of my implementation.

Appreciation to all those who can offer assistance.

Answer №1

What is causing the breakdown in your process? Is your Javascript effectively sending the Ajax request and receiving the response?

Is data being fetched into lines at this particular line of your code?

 var lines = file.responseText.split("\n");

If you have reached this point, loop through lines and add options like shown below:

var select = document.getElementById('id');
select.options.add(new Option(lines[i]));

I made some modifications to your writeDropDownList method: I included a function that will be executed once your Ajax call is finished. Within that function, you should examine the response string and append the options to your select box

base.writeDropDownList = function(file, method, path) {

    var file = upload.requestAjax();    
    file.open(method, path, true);    
    file.onreadystatechange = requestComplete;
    file.send(null);    
}
  requestComplete()
  {
    if (file.readyState == 4) 
    {
       if(file.readyState == 200)
       {
           var lines = file.responseText.split("\n");
           //foreach loop to populate select
       }
   }                            
 }

In your code, you are referencing and utilizing files.responseText before even dispatching the Ajax request with files.send(null)

EDIT:

Additional comments on your code:

  • Within the createCountriesList function, you instantiate file and assign it a value by invoking requestAjax. Then you pass it to the writeDropDownList function where you once again assign it a value by calling requestAjax. Do you notice the redundancy here? There is no necessity to create file in createCountriesList and transfer it as an argument. Simply create it once within writeDropDownList.

  • In writeDropDownList, you invoke upload.requestAjax(). What is
    upload? I do not see any initialization of upload anywhere. Did you mean to execute base.requestAjax() instead?

  • You've defined a function base.OnReadyStateChange, but there's no indication in your code instructing the AJAX request to activate that function when the state changes. Refer to the code snippet provided above for guidance. The added function requestComplete accomplishes that, and the AJAX request is directed to call it using

    file.onreadystatechange = requestComplete;

  • You set method to GET, yet you are not passing any GET values in your URL

  • Within file.open(method, path, true);, the parameter path should be the URL of the script that the AJAX request will summon. You have specified path as ../includes/_notes/countries.txt. An AJAX request cannot access a .txt file since they are non-executable.

After reviewing your code source, it appears to be quite flawed. It is advisable not to utilize it.

Why are you referring to countries.txt? Are you aiming to populate a dropdown with a list of all countries or specific countries based on user input?

If it is for the former, Javascript / AJAX is unnecessary. PHP code must be added to your html to fill the select box.

If it is for the latter, your AJAX request should transmit the user input as a GET variable.

Answer №2

Here are some thoughts to consider:

  1. Your code is clean and easy to read - great job!
  2. Consider choosing a more unique name for your namespace instead of base. This will help avoid any potential conflicts with other variables in the future.
  3. If you're new to creating HTML elements with JavaScript, start by experimenting with simple HTML examples first. Once you understand the structure, dive into using document.createElement().
  4. Take a look at popular frameworks like jQuery or Prototype. They can simplify many mundane tasks and streamline your development process.

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

Navigating through React-router with multiple child elements

Creating one of my routes requires the presence of two children in order to function properly. The main application page, where I set up all the routes, might look something like this: <Route path="/logs" component={Logs}> <Route path="/logs ...

The functionality of Dompdf's style does not seem to be functioning properly

I've been experimenting with dompdf and while my script successfully generates a PDF document, the style tag seems to have no effect. Here's my code. I'm familiar with how it operates and have used it with pure HTML before, but this is my fi ...

When I try to refresh the page in the browser, the back button in Ionic is mysteriously missing

I am currently working on a project using Ionic. While testing the app in the browser, I encountered an issue where the back button disappears after navigating to the child state of one view and then refreshing the page. Upon inspecting the "$ionicHistory" ...

Use javascript/ajax to submit the form on a separate page

I'm trying to use ajax to submit a form on another page, but my code doesn't seem to be working. Here is what I have: Send(); function Send() { var abc = document.getElementsByClassName("main"); for (var i = 0; i < abc.length; i++) { var ...

Layering one canvas on top of another

Here is the code I am working with. With a JavaScript library, I can draw on the first canvas and then merge it onto the second canvas. My question is, how can I make the first canvas stay in place or float, regardless of where I scroll on the second canv ...

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

The CSS property input::-webkit-outer-spin-button adjusts the margin-left and is exclusively visible in Chrome browser

Strange things are happening... Let me share the code for my inputs: #sign_in input#submit { height: 56px; background-color: #88b805; font-weight: bold; text-decoration: none; padding: 5px 40px 5px 40px; /* top, right, bottom, left ...

display html once the component is finished rendering in Angular 2

After making an API call in my app component and receiving a response, I need to determine which div to display and which one to hide. However, the HTML is rendered before the component process is complete. Here is an example of the code: user.service.ts ...

Utilizing the Authorization Header in WebSocket within a React Electron Application

Struggling to establish a connection with a secure websocket that requires Bearer Auth via Header. Despite popular advice, it seems setting headers for WebSockets is not straightforward. How can I achieve this in a React Electron App? Currently using the & ...

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...

Indeed, validation under certain conditions

How can I validate an event using yup validatesync? The input is an object that contains another object with 3 fields. The first field is required, and either field 2 or 3 should be present in the input, or use the default value. In the code snippet belo ...

Using Vue and vue-multiselect to create interactive options based on the selected language

I'm currently developing a Vue website with multilingual support. The chosen language is stored in a Vuex store and accessed through the computed property lang, like so: lang(){ return this.$store.state.lang } I use this lang property in v-if cond ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

HTML/CSS: There is a sentence that has no spaces that is exiting outside a div

HTML: <div> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb </div> CSS: div { width: 150px; border: 1px solid blue } DEMO: http://example.com QUESTION: How can we solve this issue? ...

Interactive HTML5 forms with movable fields on mouse click

I'm dealing with a specific issue in IE11 that's been really frustrating. Take a look at the form image below: Everything works fine except for when users interact with form fields in the right column on IE11. It causes input fields in the left ...

ng-model assigns the value to the select

Below is the angularjs directive I have created: dicApp.directive('listpanel', function ($resource) { return { restrict: 'E', template: '<select ng-model="selectedDictionary" ng-change="listChange()">&apo ...

What is the best way to hide certain buttons from specific users in Angular using the If condition?

I am facing an issue with my array of blocked_users, where I need to hide certain buttons if a user is in the blocked_users list. Below is the code snippet from my angualr.component.html: <div *ngIf="!(userId in event.blocked_users)"> ...

What is the best way to export an object that is exclusively accessible within an asynchronous callback function?

In my project, I have a db.js file that handles establishing a connection to a MongoDB database. My goal is to export the database object from db.js to be used in my main app.js file: // Inside db.js require('mongodb').MongoClient.connect(/* the ...

Incorporating a discreet progress bar into traditional file uploading processes

Have you noticed the trend of new, advanced file uploaders, many of which are Flash-based like SWFUpload? These uploaders can display a progress bar while files are being uploaded, making it much easier for users with shaky or low-bandwidth connections. H ...

Is it possible to overlay a three.js scene onto an HTML video element?

A project I am working on involves developing an AR app that can display markers for North, East, South, and West using a smartphone camera. The goal is to create a scene with a transparent background that can be overlayed on a video feed from the camera. ...