Ways to implement callbacks in various functions within JavaScript

Having trouble figuring out how to access a variable inside a callback function from another function located outside of the callback...

To simplify the issue:

There is a function that retrieves JSON data from the web with some predefined arguments. Upon success, a callback function manipulates the data slightly. Another function responsible for updating a chart needs to receive the manipulated data from the callback and perform its own actions...

Here's my code snippet:

var mainData;

function getMainData(city, callback) {
  this.city = city;
  var url = "http://api.openweathermap.org/data/2.5/weather?q=appid=7ce3e1102e1902e0f878c2a640e95aed&london";

  $.ajax ({
    method:  "GET",
    type:    "json",
    cache:   "false",
    url:      url,
    success:  callback
  })
};

function callback(data) {
  mainData = data;

  var dArray = data.list.map(a=>a.dt)
  var tempMinArray = data.list.map(a=>a.main.temp_min)
  var tempMaxArray = data.list.map(a=>a.main.temp_max)
}

function changeChart(chartName, howToPassTempMinArrayHere?) { 
  chartName = chart.name.(....);
  someDataFromMainData = chart.data.(....);
};

// on click of button (...) : 
(
getMainData(callback); // why no action?? nothing??
changeChart (myChart, someDataFromMainData)
);

Answer №1

Here's an example of how to include the callback within the function:

var mainData;

function getMainData (city, callback) {
  this.city = city;
  var url = "http://api.openweathermap.org/data/2.5/weather?q=appid=7ce3e1102e1902e0f878c2a640e95aed&london";

  $.ajax ({
    method:  "GET",
    type:    "json",
    cache:   "false",
    url:      url,
    success:  callback
  })
};

function callback (data) {
  mainData = data;

  var dArray = data.list.map(a=>a.dt)
  var tempMinArray = data.list.map(a=>a.main.temp_min)
  var tempMaxArray = data.list.map(a=>a.main.temp_max)
  
  // Your code goes here
  changeChart (myChart, someDataFromMainData)
}

function changeChart (chartName, howToPassTempMinArrayHere?) { // <--- at this point, it's unclear how to pass callback variables
  chartName = chart.name.(....);
  someDataFromMainData = chart.data.(....);
};


// When button is clicked (...) : 
(
getMainData(callback); // Why no action?? No response??
);

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

How can I tailor the child count in ag grid to fit my needs?

Currently, I am using ag grid with React and have successfully implemented row grouping. However, the parent rows are displaying child row counts in numeric values. Is there a way to customize the style of the row count? Additionally, I am interested in ca ...

Add video details to the database using the API

I currently have my own database of YouTube videos which includes the video IDs found in the video links. My goal is to find a way to insert both the title and description of these videos into the database using the YouTube API and MySQL. Although I have ...

Tips for successfully implementing Typeahead with Bloodhound and a JSON response

Looking for guidance on integrating typeahead.js with bloodhound.js to leverage my JSON data structure. My goal is to implement a type-ahead feature utilizing a preloaded JSON object that remains accessible. Here's the breakdown: The Data/All URL res ...

The functionality of the Bootstrap 5 dropdown button remains elusive, despite including all required scripts within the index.html file

I'm currently working on incorporating a dropdown button into my React project. Utilizing Bootstrap 5, I have already included the necessary jQuery and Bootstrap scripts. Below is the code snippet I've developed to create a dropdown button: < ...

The response cannot be processed by the jQuery ajax() function

I've been attempting to handle the response body of an ajax call made with jQuery, but I haven't had any luck so far. Here is the jQuery code I'm using: function doAjaxClosedStatus(url, requestId, closedStatusId) { $.ajax({ type: "POST ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

Upon the completion of an ajax submission, automatically scroll to the top of the form

Similar Inquiry: How to Scroll to Top after Loading Ajax Content I am facing an issue with my ajax form. After submission, error or success messages are displayed. I want to automatically scroll the browser to the top of the form so that the user can ...

Utilize the power of PIXI.js to effortlessly convert your canvas into a high-quality image without encountering

I'm currently working on exporting the entire canvas as a PNG using PIXI.js within a React app that incorporates react-pixi. My version is 6.5 and I've been trying out the following code: // MyComponent.tsx <button onClick={exportImage} /> ...

I keep encountering an Uncaught SyntaxError: Unexpected token < error in my bundle.js file

Currently, I am in the process of creating a boilerplate for React web applications. However, whenever I try to access http://localhost:8080/, I encounter an error stating: Uncaught SyntaxError: Unexpected token < in my bundle.js file. I'm unsure ...

Vue and Summernote issue: Model content doesn't display in form when loaded from database

I am having an issue with my form that uses the Summernote wysiwyg editor multiple times. When I fill out the form, everything works correctly - the model is updated, content is displayed, and the data is saved to the database. However, when I try to edit ...

How can we rearrange the newly added row from onRowAdd in Material Table to be displayed at the beginning of the section?

Title. According to the documentation for material table, when using editable with onRowAdd, the new row is always added at the bottom of the section. Is there a way to have it appear at the top instead? Alternatively, how can I add an onClick effect so t ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

`Incorporating ordered indices within two ngFor loops?`

Below is a demo code where I am explaining my goal through comments: product.component.html <div *ngFor="let item of items1"> <div *ngFor="let item of items2"> <input type="text" value="{{data[getNumber()]}}"> //I aim to fe ...

Utilize jQuery ajax to handle form and URL processing via a GET request

When it comes to processing forms, I want to use the jQuery $.ajax GET method so that the query parameters are included in the URL. If I handle the form without using jQuery, achieving this is not a problem. However, when I utilize jQuery's $.ajax met ...

Resolving the problem of unused require statements in a TypeScript project with Socket.IO

As I delve into learning Typescript and transitioning my Node.js server code to Typescript, I've come across a few challenges (or uncertainties). One thing that perplexes me is the prevalence of tutorials favoring Yarn over npm when working with T ...

AJAX enhancing the functionality of the webgrid with dynamic filtering

I'm encountering a problem with implementing JS on my webgrid for sorting purposes. The scenario is that a user enters a string into a textbox and the webgrid below is refreshed (filtered based on matching results) without the entire page being refres ...

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...

Wondering how to optimize FullCalendar for mobile and touch events?

I am looking to incorporate a drop event feature into the mobile version of fullcalendar. To achieve this, I am utilizing Jquery UI Touch Punch. After researching on various platforms such as Stack Overflow 1, Stack Overflow 2, Stack Overflow 3, Stack Ove ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Moving Cursor Automatically to the End Upon Rejecting Input

I have a form input where users can enter values. I need to validate the inputs to ensure they only contain numbers, dots, and commas. If the input is invalid, I want to prevent it from being stored in the input field. To achieve this, I have implemented ...