use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated.

//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
  .then((eip) => {
    return eip.json();
  }).then((eip) => {
    document.getElementById('ip').value = eip.query;
    var myip = document.getElementById('ip').value;
    var url = "https://api.pray.zone/v2/times/today.json?ip=" + myip;
  })

//Get City
fetch(url)
  .then((res) => {
    return res.json();
  }).then((res) => {
    document.getElementById('city').value = res.results.location.city;
  })

While I am able to obtain the IP address successfully, retrieving the city information seems to be posing a challenge for me.

Answer №1

url is only accessible within the .then callback and ceases to exist upon calling fetch for the second time.

To properly chain the fetch calls, make sure to call the second fetch inside that callback and return the promise it generates:

//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
  .then((eip) => {
    return eip.json();
  })
  .then((eip) => {
    document.getElementById('ip').value = eip.query;
    var myip = document.getElementById('ip').value;
    return fetch("https://api.pray.zone/v2/times/today.json?ip=" + myip);
  })
  //Get City
  .then((res) => {
    return res.json();
  })
  .then((res) => {
    document.getElementById('city').value = res.results.location.city;
  })

Related: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Answer №2

Your script is asynchronous and you're triggering the fetch function before obtaining the URL.

//Retrieve IP address
fetch('https://extreme-ip-lookup.com/json/')
  .then((eip) => {
    return eip.json();
  }).then((eip) => {
    document.getElementById('ip').value = eip.query;
    var myip = document.getElementById('ip').value;
    var url = "https://api.pray.zone/v2/times/today.json?ip=" + myip;
    fetch(url)
      .then((res) => {
        return res.json();
      }).then((res) => {
        document.getElementById('city').value = res.results.location.city;
      })
});

Answer №3

When the url variable is not in scope, you end up passing undefined into the second fetch call. To rectify this issue, consider moving the second fetch before the closing of the first fetch. Alternatively, you can define the url variable outside of the first fetch and initialize it to an empty string. Then, assign the actual url value or build the url before the first fetch closes. This approach allows you to maintain separation between the fetch APIs as you currently have them structured.

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

Tips for displaying JSON in C# using Nancyframework

I am facing an issue with displaying data from a JSON file named file.json on my screen when I access the URL localhost:8080/data. The attempted solution resulted in an error being displayed on the webpage as shown below: System.Collections.Generic.List` ...

What is the best way to ensure that a child div can expand to fit within the scrollable area of its parent div

I am facing an issue with a parent div that changes size based on the content inside it. When the content exceeds the initial size, causing the parent to scroll instead of expanding, I have a child div set to 100% width and height of the parent. However, t ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

The body parser is designed to efficiently parse and handle both gzip and json formatted HTTP POST request bodies

I've set up an API endpoint to manage http POST requests from a client. At the moment, I'm using Express framework and bodyParser to handle request bodies. What I need help with is configuring body-parser to effectively handle cases where request ...

Terminate the execution of the process.exec function

Currently, I have a function in my code that is responsible for executing a specific process. Here's how it looks: static async runTest() { await process.exec(`start ${currentDir}/forward.py`); } runTest(); Here's the thing – once this Python ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

The process of loading and saving extensive data to the local storage of a user's Firefox browser involves extensive reading and writing operations

Our team has developed a sophisticated HTML5 offline application that houses a substantial amount of data, totaling tens of megabytes. We are looking for a way to allow users to save and retrieve copies of this data on their disk. While we have made some ...

How to retrieve response cookies using RxJS Ajax

When using RxJS to make an Ajax call request, I am able to set the headers of the request. However, I am wondering how I can retrieve the Cookie from the RxJS Ajax Response? import { ajax } from 'rxjs/ajax'; ajax({ url: "some url", body: ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

Utilizing jqGrid row identifiers and personalized details using JSON dataset

I'm currently facing an issue with using jqGrid along with JSON data that is returned from the server. Within my grid, I am displaying various types of objects. However, due to the nature of these objects, it is possible for two different objects to ...

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

Receiving Request URL from XMLHttpRequest in PHP

I'm currently facing a dilemma as I work on a JavaScript script that is responsible for sending data from one of my forums to the server where a PHP script runs. The goal is to have the PHP script determine which JS output should be generated based on ...

Sending cookies via POST/GET request with Credentials is not functioning

Greetings, despite the numerous duplicates of this inquiry, my attempt to solve it has been unsuccessful. Therefore, I am initiating a fresh discussion. Aside from utilizing axios, I also experimented with fetch but encountered similar outcomes. On the b ...