Struggling to retrieve the proper return value from my API request

Currently, I am utilizing the API in an attempt to retrieve an object containing both a person's city and country information. Here is my existing code:

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;


var Person = {
    city: function() {
        $.getJSON(locationAPI, function(data) {
            return data.city;
        });
    },
    country: function() {
        $.getJSON(locationAPI, function(data) {
            return data.countryCode;
        });
    }
};

var x = Person.city;
console.log(x); });

The current output looks like this:

function () {
        $.getJSON(locationAPI, function(data) {
            return data.city;
        });
    }

I am aiming for it to display a specific value such as - Person.country = USA. What could be the issue with my implementation?

Answer №1

It seems like the issue lies in misunderstanding .getJSON as a simple function when it is actually a promise function. There are two ways to retrieve the data - either through a callback function or through a promise.

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;
var Person;

$.getJSON(locationAPI, function(data) {
  Person = {
    city: data.city,
    country: data.country
  };

  var x = Person.city;
  console.log(x);
});

});

Alternatively, you can use a promise like this:

var theCall = $.getJSON(locationAPI);

theCall.done(function(data) {...})

If you choose to use .ajax() method with async set to false, be aware that it will cause the code to wait for the ajax call to finish before continuing. This can result in delays of a few seconds.

However, blocking the browser in this manner is not recommended due to potential slowdowns caused by waiting for the call to complete.

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  success: function(data) {
    //stuff
    //...
  }
});

For more information, refer to the ajax documentation or visit Is it possible to set async:false to $.getJSON call

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

Exploring the possibilities of combining mixitup with Vue.js 2.0 Component

Struggling to implement mixitup on vue.js; however, every time I check the mixitup target, it shows 0 elements in the container (mixer.getStatus().totalShow) Below is my complete vue.js component code: <template> <section class="main-co ...

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Prevent users from copying and pasting text or right-clicking on the website

I have been struggling to completely disable the ability for users to copy and paste or select text on my website across all devices. After much searching, I came across a solution that I implemented on my site. Below the <body> tag, I inserted the ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

What is the reason for needing to export the function when importing a module in an Angular appModule?

I came across the following code snippet @NgModule({ declarations: [ ... ], imports: [ RoutingModule, SharedModule, JwtModule.forRoot({ config: { headerName: 'Authorization', tokenGetter: () => lo ...

AngularJS sending unsupported media type to SpringMVC controller

Encountering an error while attempting to post JSON data from an AngularJS controller to a SpringMVC controller. Despite trying various solutions found online and ensuring that the jackson library is in the classpath, the issue persists. It's worth no ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

Transmit information from javascript to the server

I am currently working on an ASP.NET MVC web application and have a query: If I have a strongly typed view and I submit it, the object (of the strongly type) will be filled and sent to the server. But what if one of the properties of the strongly typed i ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

Tips for selecting React component props based on a specific condition

Here is a React component that I have: <SweetAlert show={this.props.message} success title={this.props.message} onConfirm={this.props.handleCloseAlert}> </SweetAlert> Upon using this component, I receive the following alert ...

Why isn't this Java page displaying the data I need from this Json file?

Hey friends, I'm facing a major issue with my project. I've made an OkHttp request and received a response from the server successfully. However, I'm unable to display the data on my model item in XML and listview (the required view). Whenev ...

How can I retrieve the PHP response once a successful upload has occurred using DropzoneJS?

I am currently in the process of integrating Dropzone into my website. My goal is to capture the "success" event and extract specific information from the server response to add to a form on the same page as the DropZone once the upload is finished. The k ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Adjust the color scheme of the active button in angularjs to create a fresh new

Here is the code snippet I am using to highlight the color of the currently active page button: <li ng-repeat="pageNumber in pages track by tracker(pageNumber, $index)" ng-class="{active :pagination.current == pageNumber, disabled : pageNumber == ...

Tips for Identifying Connection Type using JavaScript

My browser is not receiving the current connection type when using the following function. I don't think there is an issue with getting the value in ScriptNotify, as other functions are working fine with this method. It appears that navigator.connecti ...

Exploring the concept of JavaScript nested promise scopes within the context of AngularJS

I've been struggling with JavaScript promises for the past few hours, trying to fix a problem that I just can't seem to solve. My knowledge of promises is limited, so I'm open to the possibility that my approach might be incorrect. Currentl ...

I encountered a permission error while trying to npm install, despite running the command with root privileges

After running npm install as root, I am still encountering permission errors. This is unfamiliar territory for me. I have attempted using chmod -R 777 *, and chown nobody:nogroup -R * within the project folder, but to no avail. Here's the specific er ...

unable to locate express router

Recently, I set up an express project using the express generator with the following commands: express project_name and npm install Here is a snippet from my app.js file: var express = require('express'); var path = require('path') ...