Populate Dropdown With AJAX JSON (Simple Example)

Welcome to a quick tutorial on how to populate an HTML dropdown list with AJAX and JSON. Need to dynamically load the dropdown options from the server? No problem, it is actually a simple process – Read on for the example!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/populate-dropdown-ajax-json/” title=”Populate Dropdown With AJAX JSON” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

AJAX LOAD DROPDOWN OPTIONS

All right, let us now get into the example of dynamically loading the dropdown options using AJAX and JSON.

 

PART 1) THE HTML

1-page.html
<select id="demo"></select>

Nothing to see here, just the regular empty <select> with no options.

 

PART 2A) AJAX FETCH

2a-fetch.js
// (A) FETCH DATA FROM SERVER
fetch("3-data.json")
 
// (B) PARSE JSON
.then(res => res.json())
 
// (C) LOOP THROUGH DATA & GENERATE OPTIONS
.then(data => {
  let select = document.getElementById("demo");
  data.forEach((item, i) => {
    let option = document.createElement("option");
    option.innerHTML = item;
    select.appendChild(option);
  });
});

To fire an AJAX request to the server, we can use fetch(). This is seemingly complicated at first, but keep calm and look carefully.

  1. Specify the URL to fetch the data from.
  2. Parse the JSON response from the server.
  3. Lastly, loop through the parsed array of data and create the options.

 

 

PART 2B) AJAX XML HTTP REQUEST

2b-xhr.js
// (A) NEW XMLHTTPREQUEST OBJECT
var xhr = new XMLHttpRequest();
xhr.open("GET", "3-data.json");
 
// (B) PARSE JSON & CREATE OPTIONS
xhr.onload = () => {
  let data = JSON.parse(xhr.response),
      select = document.getElementById("demo");
 
  data.forEach((item, i) => {
    let option = document.createElement("option");
    option.innerHTML = item;
    select.appendChild(option);
  });
};
 
// (C) GO!
xhr.send();

Alternatively, we can also use the good old XMLHttpRequest to fire an AJAX request. A little bit long-winded, but it does the same thing as fetch.

 

PART 3) DUMMY JSON DATA

3-data.json
["Apple","Blueberry","Cherry","Durian","Elderberry"]

Finally, this is just a dummy JSON-encoded array of fruits. It does not matter which server-side language you are using. Just JSON encode the data array and output it.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

FETCH & XHR – WHICH ONE SHOULD WE USE?

Well, both of them work. For the uninitiated:

  • XMLHttpRequest is the “traditional version”. It is very stable and well-supported even in older browsers.
  • fetch is the “modern version”. It has more features but is not supported in older browsers.

So it’s up to you – I have personally moved on to using fetch.

 

COMPATIBILITY CHECKS

This example will work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Populate Dropdown With AJAX JSON (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *