Skip to content Skip to sidebar Skip to footer

Populate Drop Down Menu From File Html

Have been trying to do a simple drop down menu populated from a file where I would have an id and a list of names associated with that id: ex: id, names 1, ['John', 'Maria', 'Mari

Solution 1:

I'm gonna use php for this demo.

First it's better to use JSON format when sending and receiving data, but of course if you want to do it in any other way feel free to do so.

Javascript call to get for that data, i'll be using fetch() to make the ajax call if you don't quite understand what is it or what's ajax at all, i suggest you Check this

Let me know if you have any questions.

people.json :

{"1":["John","Maria","Mario"],"2":["Fabio","Gary","Yanni","Charlie"]}

Javascript :

// making ajax call to data.php which we will look at laterfetch('people.php')
// get data as json
    .then(rawdata => rawdata.json()) 
// here i'm just logging it, but you can do whatever you like with it.
    .then(data =>console.log(JSON.parse(data)));

people.php :

// reading file `people.json` content like you would read any file in php$data = file_get_contents('people.json');
// parsing it to json (array basically) $manage = json_decode($data);
// printing the array to the document // which is basically the response to the ajax call
print_r($data);

EDIT :

Or if you don't have any work to do on the data in the back end, you can just request the file directly from the Javascript

fetch('data.json')
    .then(rawdata => rawdata.json()) 
    .then(data =>console.log(JSON.parse(data)));

Post a Comment for "Populate Drop Down Menu From File Html"