Within my JavaScript function, I am able to retrieve a country code and its corresponding geometry based on the country name from a JSON object. This allows me to dynamically add the country border and store the country code when a country name is selected.
The country border is successfully added and the code is accessible within the function itself.
However, I encounter an issue when trying to access the variable code
outside of the function. It returns undefined
. How can I ensure that code
is recognized outside of this function and available for use in other functions?
Despite trying various approaches like creating the variable outside of the function, returning it, and calling the function again, I still feel stuck!
My attempts include referencing endless Stackoverflow posts for solutions...
I'm feeling quite puzzled at this point.
var code;
$("#innerSelect").on("change", () => { //Handles changing the country select.
addCountryBorder($("#innerSelect").val()); /* Calls function that adds country border to map */
countryInfo($("#innerSelect").val());
// Ajax call to retrieve country coordinates based on the selected country name
$.ajax({
url: "libs/php/getCoordsFromCountryName.php",
type: "GET",
dataType: "json",
data: {
countryName: $("#innerSelect").val(),
},
success: function(result) {
// Handle success response
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
// Function to add country border and retrieve country code
function addCountryBorder(countryName) {
// Ajax call to retrieve country border details
$.ajax({
url: "assets/geojson/countryBorders.geo.json",
type: "GET",
dataType: "json",
success: function(result) {
// Processing the retrieved country data
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
// Function to retrieve country information based on the code obtained
function countryInfo() {
// Ajax call to fetch country information
$.ajax({
url: "assets/php/countryInfo.php",
type: 'POST',
dataType: 'json',
data: {
country: code,
},
success: function(result) {
// Processing the retrieved country information
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
console.log(textStatus)
console.log(errorThrown)
}
});
}
// The information retrieved will be displayed in a modal