Issue
I'm trying to get my <select>
element to be populated by the country names listed in my JSON file using jQuery/ajax.
<div id="navbar">
<label for="countrySelect">Select a country from the list:</label>
<select id="countrySelect" name="countrySelect">
<!--<option>...</option>-->
</select>
</div>
--
$(document).ready(function() {
console.log("Select Function Loaded.");
$.ajax({
url: 'libs/php/getCountryISO.php',
type: 'POST',
dataType: 'json',
success: function(data) {
console.log(JSON.stringify(data));
console.log("JSON stringified");
//$.each(data, function(key, countryName) {
//var option = new Option(countryName, countryName);
//$(option).html(countryName);
//$("#countrySelect").append(option);
//})
}});
});
--
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
$url='project1\libs\json\countryBorders.geo.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$decode = json_decode($result,true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $decode[''];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
--
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Bahamas","iso_a2":"BS","iso_a3":"BHS","iso_n3":"044"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-77.53466,23.75975],[-77.78,23.71],[-78.03405,24.28615],[-78.40848,24.57564],[-78.19087,25.2103],[-77.89,25.17],[-77.54,24.34],[-77.53466,23.75975]]],[[[-77.82,26.58],[-78.91,26.42],[-78.98,26.79],[-78.51,26.87],[-77.85,26.84],[-77.82,26.58]]],[[[-77,26.59],[-77.17255,25.87918],[-77.35641,26.00735],[-77.34,26.53],[-77.78802,26.92516],[-77.79,27.04],[-77,26.59]]]]}},{"type":"Feature","properties":{"name":"Canada","iso_a2":"CA","iso_a3":"CAN",
I want to access the data "name": "Bahamas"
key & value pairs (essentially each name is a country name, so pairs are like "name':'United Kingdom"
) and make each one of them an <option>
in the <select>
element in my HTML.
I wasn't sure what to put in the $decode
part, as neither 'type'
or 'features'
worked. The code console.log(JSON.stringify(data));
doesn't log and I commented out the $.each
section of my code just to try and get the first half of it working.
Solution
A couple of things are unclear to me
countryBorders.geo.json
appears to be a local file on your webserver, I don't see any reason to use curl to read it (reading local files in PHP is easier)- I don't see the value that your PHP script is adding. It basically only wastes time by parsing a JSON file, wrapping it in a layer of fake HTTP, and then re-encoding it as JSON and sending it to the client. Aside from being unnecessary, this breaks the static file caching that the browser would otherwise do for you.
- The file appears to be located in a directory that is accessible to the client, so there is no reason to involve PHP. The client could just as well request that file directly and you would not need
getCountryISO.php
at all. - The country borders file might be a bit overkill for a simple country list, but maybe you intend to use the border polygons for something, so that depends.
Assuming you would request countryBorders.geo.json
directly, your code could look like this:
$(function () {
$.get('libs/json/countryBorders.geo.json').done(function (data) {
data.features.forEach(function (feature) {
$("<option>", {
value: feature.properties.iso_a2,
text: feature.properties.name
}).appendTo("#countrySelect");
});
});
});
// Ajax mockup for the sake of the example
$.mockjax({
url: "libs/json/countryBorders.geo.json",
responseText: {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Bahamas",
"iso_a2": "BS",
"iso_a3": "BHS",
"iso_n3": "044"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": []
}
}, {
"type": "Feature",
"properties": {
"name": "Canada",
"iso_a2": "CA",
"iso_a3": "CAN",
"iso_n3": "124"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": []
}
}]
}
});
$.mockjaxSettings.logging = 1;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/2.6.0/jquery.mockjax.min.js"></script>
<label for="countrySelect">Select a country from the list:</label>
<select id="countrySelect" name="countrySelect"></select>
Answered By - Tomalak Answer Checked By - David Goodson (WPSolving Volunteer)