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

Issue with aligning items vertically using CSS and Javascript

I must admit, I am not well-versed in CSS. My goal is to create a performance bar using CSS and Javascript. So far, I have managed to generate a background bar with another bar inside that fills up to a specific percentage. However, my issue lies in the fa ...

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

Perform a Node.js GET request following a previous AJAX POST request

Having a major issue with using AJAX... I am not receiving the expected 304 page after a successful AJAX request... here is my code snippet: $.ajax({ url: "/crawling/list", type: "POST", dataType: "json", ca ...

How to Retrieve Content from an iFrame Using jQuery?

I am facing a challenge with an HTML form that is directed to an IFRAME upon clicking "submit". The iframe then loads a page after the submission, which indicates whether the user-input data is valid or not. It simply displays on screen as "TRUE" or "FALSE ...

jQuery plugin for manipulating and adding days to dates

Within my Ruby on Rails application, there is a specific field where users can input a date. The current format for this date value is as follows: $('#search_form_handover_date').val() #returns "15-07-2014 09:00" I am looking to modify this dat ...

Various results can be produced based on the .load() and .resize() or .scroll() functions despite using the same calculation methods

I'm currently working on developing my own custom lightbox script, but I've hit a roadblock. For centering the wrapper div, I've utilized position: absolute and specified top / left positions by performing calculations... top: _center_ver ...

Organize Development and Production files in npm or webpack for improved efficiency

In React Native projects, we typically use index.android.js and index.ios.js to differentiate between the same file for Android and iOS platforms. But I wonder if it's possible to separate files based on the development and production environments as ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Something is overriding the style created by makestyle material UI that I had implemented

How can I increase the importance of my makeStyles classes over default Material UI styles? Here is my code: import { createTheme, ThemeProvider } from '@mui/material/styles'; import { makeStyles, createStyles } from '@mui/styles'; co ...

Generate random floating numbers at intervals and calculate their sum

I've been given a task to complete. Upon page load, there should be 10 fields labeled as A, B, C, D ... each with the initial value of 3. After the page has loaded, every 2 seconds all field values should change randomly. The change will be a rand ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Having Trouble Retrieving Data from MySQL through Ajax PHP and jQuery

Having asked this question previously without receiving a satisfactory answer, I am seeking assistance once again. Within my MySQL database, I have two tables named Items and Item as outlined below: I possess two .php files: index.php and results.php. The ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

MySQL stored procedure called through AJAX/PHP is not returning expected values

After dedicating several days to this task, I am now seeking assistance. My goal is to utilize Ajax/PHP/MySQL to display only a specific subset of a table based on the user's selections from a dropdown menu. The PHP code invokes a MySQL stored procedu ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Issues with logging functionality in my React Native application

I am currently facing an issue with my React Native app running on the Android Studio emulator. The logging does not appear in my terminal or in the active remote debugger in Chrome when debugging is enabled. When I attempt to log a simple text in one of m ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...