0

I apologise in advance for this question as I know it is a widely asked question, but even with all my attempts - it will not work!!

I have the variable currency which I want to make global. I set the value of currency within the countryInfo function. It returns as expected within the function, but outside of the function its undefined

var currency; 

// ----- Function responsible for grabbing country name & code to populate information modal -----//
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);
            let code = JSON.stringify(countryFeature.properties.iso_a2)
            let countryCode = JSON.stringify(countryFeature.properties.iso_a2).replace(/"/g, "")

            console.log(code)
            console.log(countryCode)

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

                    let capitalCity = (result['data'][0]['capital']);
                    console.log(capitalCity)
                    currency = (result['data'][0]['currency']);
                    console.log(currency)
etc
[end of function].

console.log[currency]

I can't understand what I'm doing wrong when what I'm doing seems to work for others?

  • 1
    [Making the variable global does not make your function call synchronous](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Lain Nov 02 '22 at 13:57
  • Your console.log will be called before your ajax call is ready. – BeSter Development Nov 02 '22 at 13:59

0 Answers0