I am currently working on a project with PHP, JavaScript and jQuery and have come across an issue. I am trying to get the PHP function getCountryBorders() to return just the polygon information for a country but I cannot seem to access object data with object['property'] as it gives me the
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21
Any help would be greatly appreciated.
Here is the code:
server.php:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
if(isset($_POST['iso_a2'])) {
$iso_a2 = $_POST['iso_a2'];
}
switch($action) {
case 'populateSelect' : populateSelect();break;
case 'getCountryBorders' : getCountryBorders($iso_a2);break;
};
};
function populateSelect() {
$data = file_get_contents('../../data.json');
echo $data;
}
function getCountryBorders($iso_a2) {
$data = file_get_contents('../../data.json');
echo $data['features'];
}
?>
//index.js
$('#document').ready(() => {
$.ajax({
url: 'libs/php/server.php',
type: 'POST',
dataType: 'json',
data: {
action: 'populateSelect'
},
success: (result) => {
result['features'].forEach((country) => {
$("<option>", {
value: country.properties.iso_a2,
text: country.properties.name
}).appendTo('#countries');
})
}
});
});
$('#countries').change(() => {
console.log($('#countries').val());
});
$('#test').click(() => {
alert('Clicked')
$.ajax({
url: 'libs/php/server.php',
type: 'POST',
dataType: 'json',
data: {
action: 'getCountryBorders',
iso_a2: $('#countries').val()
},
success: (result) => {
console.log(result);
}
});
});
The issue is within the $('#test') ajax function.
Thank you,
Liam
I have tried looking at network responses but they just return
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21
json_decode()
->
to access property items like$object->property
instead of$object["property"]
or pass true as the second argument of json_decode to convert it to an array