0

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.

8
  • can you share a more exact example of data? Commented Aug 12, 2021 at 15:06
  • Hi, I think I understood what you meant, I added more of the JSON file content to display the data. I've also added a PHP file to my project to try and help decode ithe JSON file further Commented Aug 12, 2021 at 15:29
  • 1
    @Kizzy: Are you saying that the PHP code is throwing an error and not returning the expected data? If that's the case then this really has nothing to do with what's being asked in the question because something is failing server-side. Commented Aug 12, 2021 at 15:53
  • 2
    project1\libs\json\countryBorders.geo.json is a local file on your server, right? Question 1: Why are you using curl to read a local file? Question 2: Why are you using a PHP proxy script in the first place for sending local files to the browser? Would it not be easier to let the clients download that file directly, instead of having to go through PHP to get it? Commented Aug 12, 2021 at 16:10
  • 1
    @Kizzy: "I thought that maybe I was incorrect in thinking jQuery/javascript would be able to parse data from a JSON file" - JSON stands for "JavaScript Object Notation", it can be read natively by JavaScript. It sounds like you're drastically overcomplicating the effort at this time. If you have no other need for PHP involvement then I would recommend just fetching the JSON file itself in the AJAX operation. Commented Aug 12, 2021 at 16:25

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ever so much for this.. I knew I was absolutely overcomplicating everything, and PHP just felt like something I knew 'would work' (in a previous project I had to access an API from geonames). Maybe I should stick to Occam's Razor more.. Many thanks, once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.