A simple problem with a simple solution, I suppose. I have researced it but do not quite understand it.

Problem: I have a very nice script for a dropdown that displays country names and the associated flags for each country within a form. This works very well, but...

Examples of this code show all country/country codes embedded directly into the HTML page. While this works, it may be difficult to manage, it is too long and honestly, plain ugly.

I want to create a .txt file of the country names/country codes that lives on my server and can be called from within the HTML page. Clean.

I have read this is advised against (I do not understand why) - It is simple isolation of text to be called. How can that pose a problem or a risk?

I'm lost at this point as how to do this technically; I am assuming via Javascript/jQuery.

Thank you in advance for all help!

Matthew

Dani AI

Generated

A short practical answer: keep the country list as a small structured file (JSON is easiest) on the server and load it into the page at runtime, or render it server-side if no JS is wanted. Storing a plain text file of public data is not inherently risky — the common warnings usually mean "do not store secrets or server config in public files" or "avoid unstructured text that breaks parsing/encoding". Structured JSON avoids parsing headaches and makes mapping to country codes/flags trivial.

A simple client-side workflow (example):

  • Place a countries.json file on the server as an array of objects like [{ "code":"US", "name":"United States" }, ...].
  • Fetch that file from the page, parse JSON, and append option elements to the select (use DOM methods or textContent to avoid XSS).
fetch('/data/countries.json')
  .then(r => r.json())
  .then(list => {
    const sel = document.getElementById('country-list');
    list.forEach(c => {
      const opt = document.createElement('option');
      opt.value = c.code;
      opt.textContent = c.name;
      sel.appendChild(opt);
    });
  })
  .catch(err => console.error(err));

Notes and gotchas (fills gaps from the thread):

  • was right that structured data (XML/JSON) works; JSON is simpler today. ’s server-side approach is valid too if hiding file paths or avoiding JS is preferred. correctly noted that client-side files are discoverable — that is normal for public data.
  • Flags: avoid putting images inside native option (browser support is inconsistent). Use a custom dropdown widget or show the flag beside the select. Store flag files named by ISO alpha-2 code (consistent casing) for easy mapping.
  • Troubleshooting: ensure the JSON is UTF-8 without a BOM, serve it with application/json, check DevTools network for 404/CORS/500 errors, and set cache headers for static files. Always insert text with textContent or createElement rather than innerHTML to prevent XSS.

Recommended Answers

All 7 Replies

I don't see a problem with having a text file on your web server and then you retrieving that text using javascript/jQuery AJAX.

Can you elaborate regarding the risk you read about?

The risk. They did not state the risk. They just said that they read about it somewhere and added "LOL" - No details as why one should not implement this.

As long as your text file is secured on the web server, I can't think of any reason.

In addition, you could use a PHP array, for example create fruits.php:

<?php

    return array(

        'red' => array(
            'Cherries',
            'Cranberries',
            'Pomegranate',
        ),

        'green' => array(
            'Avocados',
            'Cucumbers',
            'Honeydew',
        ),

        'blue' => array(
            'Blueberries',
            'Fig',
            'Plums'
        )

    );

Then you can include it in your script as a configuration file:

<?php

    $fruits = include 'fruits.php';
    print_r($fruits['red']);

    foreach($fruits['blue'] as $fruit)
    {
        echo $fruit;
    }

With this structure you can create a multidimensional array with all the information about each Country and use it as you like. Bye!

commented: Thank you! +7

What I'm having trouble with is calling it from the server into the form.

I'm not exactly sure how to do this.

Thanks,
Matthew

Here is some sample code for you to work with. The are generally two ways that you want to store data jSON and XML, at least those are the two i use when working with javascript. I will store my data for this example in an XML file. You will need to files for this sample to work.

test.htm
<!DOCTYPE html>
<html>
<head>
     <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form name="myForm" method="GET" action="">
   <select id="country-list">
      <option />
   </select>
</form>
<script>
$(function () {
   $.ajax({
        type: "GET",
        url: "test.xml",
        dataType: "xml",
        success: function (xml) {
           $(xml).find('country').each(function (i) {
               var c = $(this).text();
               $('#country-list').append("<option>" + c + "</option>");
           });
        }
   });
});
</script>
</body>
</html>
test.xml
<?xml version="1.0" encoding="utf-8" ?>
<DropDown>
     <country>Australia</country>
     <country>Brazil</country>
     <country>Canada</country>
     <country>...</country>
     <country>...</country>
     <country>United States</country>
</DropDown>
commented: Thank you! +7
Member Avatar for Member #120589

Just remember that if you're using js for this all your code is visible and the locations of any files. For this I can't see a problem, however a server side solution may be easier - no need for Ajax.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.