javascript issue with accessing global variable outside of function despite multiple attempts

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

Answer №1

Eliminate the outer/global variable and implement a callback like this:

/* Modify function to add border to a specified country and retrieve country code*/

function addCountryBorder(countryName, cb) {

    $.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)
            
            console.log(code) // remove early return
            
            if (!countryFeature) {
                return cb(null, {code});
            }
            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)
            cb(null, {countryFeature,code})
        },
        error: function(jqXHR, textStatus, errorThrown) {
            cb({jqXHR, textStatus, errorThrown}
        }
    })
}

then execute it with:

addCountryBorder('some country name', (err, result) => {
    // verify if err is not null
    // result will be {code, countryFeature}
});

the above is equal to:

const cb =  (err, result) => {

    // verify if err is not null
    // result will be {code, countryFeature}

    console.log('result is:', result);
};


// pass the callback cb
addCountryBorder('some country name', cb);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting aside room for one's @property characteristics

I'm fairly new to objective-c and I could use some guidance on variable declaration. I'm working on a program that involves reading a message delivered in multiple parts of NSData. Each time the program receives a NSData, it appends it to the exi ...

Adjust the height of the element to prevent the need for a double-scroll

Currently, I have created a webpage for a client that includes a PDF using an iframe tag. The issue arises when the PDF is rather large, resulting in two scrollbars - one for the page and one for the embedded PDF within the iframe (loaded through the integ ...

Is there a way to transform a .pcm file to a wav file using node.js?

I'm working on a project that generates a pcm file from a stream and saves it after the stream finishes. Now, I am looking for a way to convert this .pcm file to a .wav or another audio format using an npm package. Can anyone suggest a solution or poi ...

How to emphasize a clicked hyperlink in AngularJS

Here's the HTML code I've been working on: <div id="Navigation" class="md-dialog-full"> <div class="products-options"> <a ng-click='addType("Physical")' href="javascript:void(0);"> < ...

Difficulty integrating Bootstrap with JavaScript file in Visual Studio Code

I am attempting to incorporate a dynamic progress bar by utilizing Bootstrap's progressbar and creating a custom JavaScript file. The goal is to continuously adjust the width of the progress bar at regular intervals to give the appearance of a moving ...

Looking for a way to execute MySQL queries using promises in Protractor?

Is there a way to query a MySQL database using promises in Protractor? I have multiple queries that I need to execute during test execution, but my `executeSelectQuery` function always runs at the beginning of the test. How can I ensure it executes at the ...

Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance: If an array index includes the title "Retail", I want to return the ...

Using Rollup alongside Typescript to handle absolute imports for type declarations

In the process of creating a React component library, the project structure resembles the following: src/ components/ utils/ hooks/ Currently, there is an attempt to generate type files (.d.ts) using rollup. The types are successfully generated, ...

The JavaScript value of the button text once it has been modified

We have a website feature where the button text changes dynamically. Here are the elements before the button text change: <button _ngcontent-wex-c70="" class="btn btn-wait buy font-family-title height-70 pp-sun-ins"><labe ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

The function $.get does not function correctly when added to Button.ClientSideEvents.Click during the second click

string okumagecmisiStr = string.Format("function(s,e){{ $.get('/GetHazirRapor.ashx?RaporTanimi={0}',function(data){{location.href='{1}'}} ); }}", hrt.ID, hrt.WebRaporLink); ButtonWebRaporAc.ClientSideEvents.Click = okumagecmisiStr; T ...

Multiple components are returned with switch case

I am trying to iterate over an object and display a result based on Object.entries. However, the loop currently stops at the first return statement. Is there a way for me to capture and display all components returned simultaneously, perhaps using a vari ...

Guidelines for establishing authentic headers on a SignalR connection

Can headers be set on the SignalR connection directly? I am aware of setting query string parameters but it is not secure enough for my specific scenario. var conn = ($ as any).hubConnection(); conn.url = URL; conn.qs = { "token": SECRET_KEY }; conn ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

What is the best way to incorporate Javascript into jQuery tabs?

On my website, I have implemented a Jquery and CSS tab system similar to the one found here. Each tab contains a Facebook feed box, a Twitter widget, and a ranking widget for my blog. However, when these widgets are placed within the tab content area, they ...

Identifying a flaw in an HTML5 video

I am attempting to identify when an error occurs while playing an HTML5 video. Specifically, I am encountering a situation where I am trying to play an HLS video on a MAC (where "canPlayType" is at least "maybe"), but the video will not play for unknown r ...

Using nightwatch.js to verify elements across different parts of a webpage

Currently engaged in working with nightwatch.js and encountering an issue with a particular page file structure: sections: { table: { selector: '.sr-filterable-data-layout--collection', elements: { header: { ...

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...

The functionality of displaying an animated gif will not work when submitting a CakePHP ajax form before or after completion

I have exhaustively tested all possible scenarios using prototype, but I am unable to get my busy indicator to show no matter what I do. Despite cross-browser testing, I've had no luck. <?php echo $ajax->submit('Submit', array(' ...