0

I am trying to write a JavaScript Function which finds the correct JSON object for a Country Name from a GeoJSON file. From this, it then extracts the Country Code. I want to then use the Country Code as a parameter to pass to an API in order to retrieve information about that country. This information is then shown in a modal

However, I seem to be getting the error SyntaxError: Unexpected token '<', "<?php - I can't figure out where I'm going wrong

JavaScript


let code

$('#innerSelect').on('change', async () => {     //Handles changing the country select.
  await addCountryBorder($('#innerSelect').val())  /* Calls function that adds country border to map */
  countryInfo($('#innerSelect').val())

  const result = await $.ajax({
    url: 'libs/php/getCoordsFromCountryName.php',
    type: 'GET',
    dataType: 'json',
    data: { countryName: $('#innerSelect').val() }
  })

  if (result.status.name == 'ok') {
    const { lat, lng } = result.data[0].geometry
    map.panTo(new L.LatLng(lat, lng))
  }
});

/* Function responsible for adding border to a given country and grabbing country code*/
async function addCountryBorder (countryName) {
  const result = await $.ajax({
    url: 'assets/geojson/countryBorders.geo.json',
    type: 'GET',
    dataType: 'json',
    data: {}
  })

  const features = result.features

  const countryFeature = findFeatureFromName(countryName)

  if (!countryFeature) return

  if (border) map.removeLayer(border)

  border = new L.geoJSON(countryFeature.geometry, {
    style: { color: '#006600' }
  }).addTo(map)

  map.panTo(border.getBounds().getCenter())
  map.fitBounds(border.getBounds())

  console.log(countryFeature)
}


function countryInfo(countryName) {
        $.ajax({
        url: "assets/geojson/countryBorders.geo.json",
        type: "GET",
        dataType: "json",
        data: {
            
        },
        success: function(result) {
            let features = result["features"];

            let countryFeature = findFeatureFromName(countryName);
            countryCode = JSON.stringify(countryFeature.properties.iso_a2)

            
            console.log(countryCode)
            
        $.ajax({
        url: "assets/php/countryInfo.php",
        type: 'POST',
        dataType: 'json',
        data: {
            country: countryCode,
        },
        success: function(result) {

                console.log(JSON.stringify(result));

                if (result.status.name == "ok") {

                $('#continent').html(result['data'][0]['continentName']);
                $('#capital').html(result['data'][0]['capital']);
                $('#countryName').html(result['data'][0]['countryName']);
                $('#population').html(formattedPopulation);
                $('#currencyCode').html(result['data'][0]['currencyCode']);


                }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}
  });
}


PHP

<?php

    // remove for production

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    $url='http://api.geonames.org/countryInfoJSON?formatted=true&country=' . $_REQUEST['country'] . '&username=username&style=full';

    $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['geonames'];
    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 

?>

HTML

<!-- The Modal -->
  <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
      
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Information</h4>
           <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>        
        <!-- Modal body -->
        <div class="modal-body">
          <h6 id="countryName" class="modal-sub-header"></h6>
          <hr>
          <ul class="dem">
            <li class="listItem">Capital City: <span class="test" id="capital"></span></li>
            <li class="listItem">Continent: <span class="test" id="continent"></span></li>
            <li class="listItem">Population: <span class="test" id="population"></span></li>
            <li class="listItem">Currency: <span class="test" id="currencyCode"></span></li>
            <li class="listItem">Area (km<sup>2</sup>): <span class="test" id="area"></span></li>
          </ul>
        </div>          
      </div>
    </div>
  </div>
  

The error in the console looks like so

SyntaxError: Unexpected token '<', "<?php

    //"... is not valid JSON
    at parse (<anonymous>)
    at ajaxConvert (jquery-3.5.1.js:9260:19)
    at done (jquery-3.5.1.js:9736:15)
    at XMLHttpRequest.<anonymous> (jquery-3.5.1.js:10047:9)

I believe the error to be to do with the countryInfo.php ajax call

  • 1
    You're getting ` – aynber Oct 26 '22 at 22:27
  • Oh sorry! The error is pointing at ```console.log(errorThrown);``` in the ```countryInfo``` function – javascript_bewildered934 Oct 26 '22 at 22:28
  • @aynber I dont quite understand? Sorry – javascript_bewildered934 Oct 26 '22 at 22:31
  • `SyntaxError: Unexpected token '<', " – aynber Oct 26 '22 at 22:33
  • @KIKOSoftware it seems to be ```countryInfo.php``` causing the issue as the ```console.log(code)``` for ```countryBorders.geo.json``` prints the expected output – javascript_bewildered934 Oct 26 '22 at 22:35
  • @aynber the URL is set up in the ```countryInfo.php``` as ```$url='http://api.geonames.org/countryInfoJSON?formatted=true&country=' . $_REQUEST['country'] . '&username=username&style=full';``` – javascript_bewildered934 Oct 26 '22 at 22:37
  • That's the URL in the PHP, but the PHP isn't working. Ignore that part at the moment. The error you're getting is from javascript saying it doesn't like what PHP is sending back, because the PHP is not processing at all. What does the URL in the browser show? – aynber Oct 26 '22 at 22:39
  • @aynber The URL should return this JSON as thats how it opens in the browser ```{"geonames": [{ "continent": "EU", "capital": "Berlin", "languages": "de", "geonameId": 2921044, "south": 47.2701236047002, "isoAlpha3": "DEU", "north": 55.0583836008072, "fipsCode": "GM", "population": "82927922", "east": 15.0418156516163, "isoNumeric": "276", "areaInSqKm": "357021.0", "countryCode": "DE", "west": 5.8663152683722, "countryName": "Germany", "postalCodeFormat": "#####", "continentName": "Europe", "currencyCode": "EUR" }]}``` – javascript_bewildered934 Oct 26 '22 at 22:53
  • @aynber http://api.geonames.org/countryInfoJSON?formatted=true&country=DE&username=demo&style=full link to the browser for your understanding – javascript_bewildered934 Oct 26 '22 at 22:54
  • **Ignore the PHP, ignore the API.** What does **your** browser show as the URL? The issue is the PHP is not being processed, `libs/php/getCoordsFromCountryName.php` is returning your code as text instead of actually running it. So you need to figure out why. Please read the linked duplicate, it gives explanations and fixes. – aynber Oct 27 '22 at 15:03

0 Answers0