What is the best way to generate a new object within a function and then return it

The function performs the following steps:

  1. Retrieves an XML document through AJAX.
  2. Identifies relevant information within the document.
  3. Dynamically converts it into an object using a for loop.

How can I access this generated object outside of the function?

Sample Code:

XML File:

<root>
 <config>
 <station>Station_One</station>
 <station>Station_Two</station>
 <station>Station_Three</station>
 </config>
</root>

JS file with station coordinates:

var stations = {

  'Station_One': {
      lat: 78.782762
    , lng: 17.917843
    , name: 'Nowhere'
  },
  'Station_Two': {
      lat: -0.829439
    , lng: -91.112473
    , name: 'Isla Isabela'
  },
  'Station_Three': {
      lat: 15.066156
    , lng: -23.621399
    , name: 'Cape Verde'
  }

Script:

function addRoute() {
    xhr = createHttpRequest(); //This function returns an XMLHttpRequest()
    var url ="urlhere"; //assume valid URL
                 xhr.onreadystatechange = function () {
                     if (xhr.readyState == 4 && xhr.status == 200) {
                     var doc = xhr.responseXML;
                     var routeStations={};
                     config=doc.getElementsByTagName("station");
                        for (i=0;config.length>i;i++) {
            //Successfully extracts station values and stores them in currentStation
                        var currentStation = config[i].childNodes[0].nodeValue;
            //currentStation is then used as a reference to find the values stored in the JS file
                            var lat = stations[currentStation].lat;
                            var lng = stations[currentStation].lng;
           //routeStations Object is created dynamically
                            routeStations[currentStation] = {lat: lat, lng: lng}
                        } //end for loop
           //alert(routeStations); routeStations object is created successfully
           // but will not be available beyond this point
           //return routeStations; did not work for me
                     } //end readyState && status

                 } // end onreadystatechange
                  xhr.open("GET",url,true);
                 xhr.send(null);
}

How do I make this object accessible by other functions?
To clarify, I aim to utilize this object in another function. The intention is to use these coordinates to draw a polyline with the Google Maps API.

Note: This function is triggered by an onChange event, therefore, a new object must be created each time the event occurs on top of the existing one.

Answer №1

function activateEventListener(){
    establishRoute(callbackRoute);
}



function callbackRoute(routeStations){
  ....
}



function establishRoute(callback) {

   xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            //lots of code to retrieve object
            callback(routeStations);
        }
   }

}

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

Calculate the occurrences of numbers within a string in an array of objects containing a specific string each time an object is removed

I am facing an issue where I need to re-number strings based on their type, regardless of their previous number. For example, if I delete Oranges 2 from [Oranges 1, Oranges 2, Oranges 3], it should become [Oranges 1, Oranges 2]. This means the numbers shou ...

Looking for a way to postpone an ajax function? If setTimeout isn't delivering the desired delay, there

Within page A, there are a total of 6 iframes. Once each iframe has finished loading, it is required to send an ajax request to page B in order to rewrite the data within the database. Subsequently, the src attribute of the current iframe should redirect t ...

Troubleshooting the issue: AngularJS not functioning properly with radio button selection to show specific div containing input field

Looking for some help with radio buttons: I need the selection of radio buttons to display their respective input boxes. I have included a snippet of my HTML and controller code below. In my controller, I am using ng-change to call a function that uses jQu ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Is there a way to trigger an ajax call specifically on the textarea that has been expanded through jQuery?

Whenever I expand a textarea from three textareas, all three trigger an ajax call. Is there a way to only call the ajax for the specific expanded textarea? I tried using $(this).closest('textarea').attr('id'), but it didn't work. A ...

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

When I implement the persist gate in Next.js with Redux, the flex direction automatically adjusts

I'm currently developing an app using next js and redux. An interesting issue has arisen - when I include PersistGate in my _app.js file, the flex direction mysteriously changes from row to column in index.js. There haven't been any modifications ...

Using ASHX to Return JSON in ASP.NET

I have implemented autocomplete functionality on my website. The JavaScript part is complete and I am able to retrieve the MembershipUser object of the matching user. Now, I need to format the JSON response as follows: { query:'Li', suggestio ...

Creating a webpage header with Javascript to mimic an existing design

I am in the process of building a website with 5 different pages, but I want the header to remain consistent across all pages. To achieve this, I plan to use an external JavaScript file (.js). The header includes the website name (displayed as an image) an ...

What is the best approach for sending a single mail value to the backend when there are multiple inputs in an Axios post request?

Would like assistance with a feature where only the input fields filled by the user are sent to the backend? Here, I have 3 email input fields and want to send only the filled ones. How can this be achieved? const App =() => { const [email,setEmail] ...

Forwarding images from a server to a client using socket.io and node.js

I am encountering an issue where I am trying to receive an image via socket.io in node.js and then forward it to a client (browser). However, the image sent through the message to the browser is not being recognized or displayed. Interestingly, if I save ...

Having trouble connecting the HTML file with the JavaScript file

This is my unique HTML file <!DOCTYPE html> <html> <head> <script src="ll.js"></script> </head> <body> <link rel="stylesheet" href="home.css"> ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

The dynamic loading of select tag options in Vue.js is not rendering properly

I'm having trouble displaying a select tag with options loaded from a Vue object. However, when I try to render it, something seems off: Here is the HTML markup for the select tag: <div class="form-group ui-model"> @Html.LabelFor(m => m ...

Bower Error: No tag found for ENORESTARGET

I'm encountering an issue with installing dependencies for bower bootstrap material design. I am facing a problem specifically with version 0.5.10, as it displays an error message ENORESTARGET No tag found that was able to satisfy ^0.5.10. When attemp ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Javascript - Conceal a Dynamic Div Depending on its Text

I have a unique table that generates dynamic Divs with ID's that count as they are created in the following format: <div id="dgpCheckDiv10_0"> <input Delete </div> <div id="dgpCheckDiv10_1"> text2 </div> Some of t ...

Numerous AJAX requests being made

I have been working on fetching the status of a running request and updating it on the page continuously while the request is still ongoing. However, I am facing an issue where the update only happens at the beginning and end of the request rather than con ...

Does IE 9 support endless local storage capacity?

I recently updated my HTML5 persistent storage (localStorage) capacity testing to address a memory exception issue in the previous version. I even created a jsFiddle showcasing it: http://jsfiddle.net/rxTkZ/4/ The testing code involves a loop: var val ...