Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gathering JSON data from external file

Tags:

json

html

jquery

I Have a JSON file named destinations.json and i would like to get the data from this file to display in a dropdown box on HTML. The JSON file is as shown below

{
    "Destinations": [
    {
        "destinationName": "London",
        "destinationID": "lon"
    },
    {
        "destinationName": "New York",
        "destinationID": "nyc"
    },
    {
        "destinationName": "Paris",
        "destinationID": "par"
    },
    {
        "destinationName": "Rome",
        "destinationID": "rom"
    }
    ]
}

So far, i have made sure the jquery library is available and then created a function which will fetch data from the JSON file when clicked, shown below.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <script type="text/javascript">

    $(document).ready(function() {

    $('#fetch').click(function() {
    $.post('http://jonathangatenby.co.uk/Candidate/json/destinations.json', {}, function(data) {
        $.each(data.Destinations, function(i, v) {
            $('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
        });
    });
});
</script>

from here, i have simple HTML which will give me a drop down box.

<select id="destinations">
    <option value="">Select</option>
</select>
<a href="#" id="fetch">Fetch JSON</a>

This doesn't seem to work, and all the files are on the same server.


1 Answers

Try this jquery code :

$(function() {
    $('#fetch').click(function(){
        $.getJSON('yourjsonfile.json', function(data) {
            destinations = data['Destinations']

            $.each(destinations, function(id, destination) {
                $('select').append('<option value="">'+destination["destinationName"]+'</option>')
            })
        });
    })
})
like image 192
Lucas Willems Avatar answered Mar 25 '26 15:03

Lucas Willems



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!