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

Creating an 8-bit grayscale JPEG image using HTML5 and encoding it from a canvas source

Is there a simple method to convert an 8-bit grayscale JPEG from Canvas using client side technologies in a web browser (such as HTML5, canvas, WebGL, and JavaScript)? Are there any pre-made JavaScript libraries available for use, without requiring extens ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Vue - Display components next to sidebar

Having an issue with the vue-sidebar-menu. The sidebar is appearing over the components instead of beside them. Here is a screenshot of the problem: <template> <div id="app"> <sidebar-menu :menu="menu" /> <vue-page-transit ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Tips for incorporating various color schemes into all sides of a shape generated through the extrude geometry feature in three.js

I have recently designed a wall-like structure using extrude geometry and now I want to assign different colors to each side based on the settings below: var extrusionSettings = { curveSegments:5, steps: 10, amount: 200, be ...

``In a WordPress plugin, a SELECT query for the database (utilizing WordPress, PHP, and MySQL) is

When trying to fetch records from a select query within a plugin, I encounter an issue where no records are returned and I receive the following error message in the web console. Can someone help me identify what mistake I might be making?: Object { rea ...

Encountering issues with subclass properties post JSON serialization crash

I encountered a strange issue during JSON serialization and object creation. The code crashes when attempting to access properties of the subclass, while properties of the superclass can be accessed without any problems. Below is the class in question: i ...

Sharing a Twitter thread using Twit library with Node.js

I have been using Node.js along with the npm Twit module to post tweets on Twitter, and while it works for a single tweet, I am facing issues when trying to post multiple tweets as a thread. When attempting to post a series of tweets together, they do not ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

The error message "Invalid JSON payload. Root element needs to be a message" is returned when using the Google Sheets API with python 2.7

I have been struggling with an error for several weeks now and have attempted solutions from previously asked questions regarding the Python API for Google Sheets. Every time I make a "write" request to my spreadsheet using the Google Sheets API for Pytho ...

How can default props be set for a nested object in Vue?

Here's how I've defined my props: myHouse = { kitchen:{ sink: '' } } I attempted to set the default props like this, but it didn't work as expected. props: { house: { type: Object, default: () => { ...

Concise way to add or insert an element into an array, at a specific property of an object

I am working with an object of the ObjectOfArrays type: type ObjectOfArrays = { [id: string]: Array<string> }; Throughout my code, I need to add strings to the correct array based on the id. Currently, I am using the following approach: if (id i ...

Saving the current state of a member variable within an Angular 2 class

export class RSDLeadsComponent implements OnInit{ templateModel:RSDLeads = { "excludedRealStateDomains": [{"domain":""}], "leadAllocationConfigNotEditables": [{"attributeName":""}] }; oldResponse:any; constructor(private la ...

Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example: User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar. The desired output would be: [4, 3, 1] This filter works ...

Storing executable scripts in HTML5 LocalStorage allows for the dynamic creation

As I work on a hybrid app with its own local HTML and JS files, there are times when I need to load additional small executable JS scripts and CSS from the server. Currently, I achieve this by using $.getScript, which has been working well. In order to ma ...

JSON object containing elements with dash (-) character in their names

While I am in the process of parsing a `json` object, I encountered an element labeled as `data-config`. Here's an example: var video = data.element.data-config; Every time I attempt to parse this specific element, an error pops up: ReferenceError ...

What causes the console.log function to behave in this manner?

When using the node.js interpreter, if you run the code: console.log("A newline character is written like \"\\ n \"."); //output will be:- // A newline character is written like "\ n ". However, if you just enter the following in ...

Showing chosen checkbox information using jQuery ajax

When a user enters more than 3 characters into a text box for live search, results are displayed from the database via an AJAX response as checkboxes with names. I want selected checkboxes to display in a separate div below so users can search multiple dat ...

Preserving the most recent choice made in a dropdown menu

Just started with angular and facing an issue saving the select option tag - the language is saved successfully, but the select option always displays English by default even if I select Arabic. The page refreshes and goes back to English. Any assistance o ...