alter URL parameters dynamically during API invocation

Is there a way to call an API multiple times in one request? I need the ability to dynamically adjust the date parameters for each call so that I can retrieve data for different days simultaneously.

While conducting research, I came across the following code snippet that saves the output of a single API request:

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

However, I am unsure how to modify this code to make multiple calls with varying date parameters and store the outputs as separate JSON objects from the API.

Answer №1

A simple solution could be to create a function that takes an argument and utilizes it twice - once for the request and again to "store" the result.

var myData = {};
function getDate(date) {
    $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date, function(data){
        myData[date] = data;
    });
}
getDate('date1');
getDate('date2');
getDate('date3');

This code does not account for the asynchronous nature of the request, which is also true for the original code in the question.

Note: I updated the name of the result object in the callback and the variable where the result is saved to emphasize that it is not JSON - even though the returned data might be JSON, jQuery.getJSON returns the parsed JSON as a regular JavaScript object.

A more suitable approach would be something like this:

function getDate(date) {
    return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
$.when(getDate('date1'), getDate('date2'), getDate('date3'))
.then(function(result1, result2, result3) {
    // the results are now available
})

If the number of calls is dynamic, the logic becomes more complex (especially with jQuery.when):

function getDate(date) {
    return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
var dates = ['date1', 'date2', 'date3'];
$.when.apply($, dates.map(function(date) {
    return getDate(date);
}).then(function() {
    // the results are in arguments[]

})

Since jQuery.getJSON returns a thenable (promise), you can simplify the code using Promise.all. To support IE, a Promise polyfill is necessary. This linked one is referenced in the MDN Promise docs, but there are many other options available.

function getDate(date) {
    return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
var dates = ['date1', 'date2', 'date3'];
Promise.all(dates.map(function(date) {
    return getDate(date);
}).then(function(results) {
    // results is an array containing all the results in the same order as the dates array
})

Answer №2

If you're looking to utilize JavaScript for iterating through arrays, consider using the following method:

jquery.each(array,callback)
callback should be a function that takes either an integer index and value of the array element, or a string property name and object value

To begin, construct the full URL including the date parameter and add them to the array. Then, proceed to apply the same function for each individual parameter within the URL array. This can be achieved using the jquery.each() method.

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

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

When incorporating babel-plugin-styled-components, Nextjs may encounter a mismatch error with classnames

After transferring the content of _document.js from the following styled components example and implementing the babel plugin mentioned in the styled components documentation, I am still encountering an error. _document.js import Document from 'next/ ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

Using Typescript: How to access a variable beyond the scope of a loop

After creating an array, I need to access the elements outside of the loop. I am aware that they are not in the scope and using 'this.' before them does not grant access. colIdx = colIdx + this.columns.findIndex(c => c.editable); this.focusIn ...

Step-by-step guide on dynamically generating table rows in React

I have been trying to dynamically create a table with rows and columns based on an array. While my rest request is functioning properly, I am facing challenges when attempting to switch from a hard-coded example to a dynamic approach using loops or mapping ...

Remove the underline from links in gatsbyjs

When comparing the links on (check source code https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark), they appear without an underline. However, on my blog (source code here: https://github.com/YikSanChan/yiksanchan.com), all links are un ...

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

How to include <li> in a preexisting <ul> using JSON data in jQuery

Here is the code snippet I am currently working with: <div id="tags"> <ul> </ul> </div> I want to add some items to the list using JSON data $.getJSON("data.json", function (data) { var html = ''; ...

Exploring the concept of returning objects in jQuery

I'm really trying to grasp the inner workings of how jQuery creates the return object when searching for DOM elements. I've delved into the source code, but I must admit that it's not entirely clear to me yet. So, I'm reaching out here ...

What is the best way to insert a two-worded value into the value attribute of an input tag using Express-Handlebars?

Currently, I am using the code below to render the handlebars page: router.get("/update", function(req, res) { mysql.pool.query("SELECT * FROM workouts WHERE id = ?",[req.query.id], function(err, rows, fields) { if (err) { c ...

Node.js user update complete

I am currently working on enabling users to edit their profiles. However, the code I have set up does not seem to be functioning as expected. The form I am using looks like this: <form action="/dashboard/users/edit/:id" method="put"> And my route ...

An index problem with BufferGeometry

Trying to transition code from openFrameworks to THREE.JS for generating a landscape with Perlin noise. The approach involves creating a static index array first, followed by positioning vertices in a square grid, each offset by a specific distance. This s ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

Tips for utilizing a .node file efficiently

While attempting to install node_mouse, I noticed that in my node modules folder there was a .node file extension instead of the usual .js file. How can I execute node_mouse with this file format? After some research, it seems like node_mouse may be an a ...

Start running additional JavaScript code only after the previous one has been fully executed

Scenario: I am facing a situation where I have a web form that is submitted through the following event listener: $('#myForm').on('valid', function (e) { ... } Within this function, I have a code snippet that fetches the geo location ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Why is it that the window object in JavaScript lacks this key, while the console has it?

let myFunction = function declareFunc() { console.log(this); // window console.log(this.declareFunc); // undefined console.log(declareFunc); // function body } console.log(this) // window myFunction(); I understand that the this keyword in a functio ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...