Your question could be interpreted differently, but I have two possibilities:
1 - Assuming that the JS script and PHP script are separated, then you need to do an http request to the server (using AJAX for example)
2 - Assuming that the JS & PHP code are in the same script, I would suggest to embed php code in the JS code as below:
<script>
...
var serverCountries = "<?php echo implode(",", countriesForJS()) ?>";
var questions = [
{
question: "What's your country?",
type: "select",
response: serverCountries.split(',')// replace the existing response by server countries
/*
response: ['India','America','Japan', ...serverCountries.split(',')]// or add server countries to the existing response */
}
];
...
</script>
EDIT (JS, PHP Scripts are separated)
In this case, I assume the server is accessible via an endpoint, and the script output could be reached by calling for example the api url below: http://[YOUR_HOST]/my_php_script.php [assuming again that the http method is GET and there is no authentication]
In this case, here is a jQuery ajax request could be done from your JS script:
(you need to import jQuery if it's not already done)
$.ajax({
url: "http://[YOUR_HOST]/my_php_script.php",
type: 'GET',
dataType: 'json', // added data type
success: function(serverCountries) {
console.log(serverCountries);
var questions = [
{
question: "What's your country?",
type: "select",
response: serverCountries
}
];
// do something with your questions variable ....
}
});
And the my_php_script.php script is something like:
<?php
function countriesForJS(){
global $pdo;
$stmt = $pdo->prepare("SELECT id, name FROM countries");
$stmt-> execute();
while($row = $stmt->fetch()){
$data[] = $row;
}
return $data;
}
$data = countriesForJS();
header('Content-Type: application/json');
echo json_encode($data);
?>