Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser:

I attempted to store the data in a variable with the following code:

$http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json').then(function(response) {
            $scope.zipCodes = response;
          });

Here is the HTML where I tried to display it:

<pre>zipCodes {{zipCodes | json}}</pre>

However, nothing seems to be displayed. Any suggestions on what could be going wrong?

I also experimented with this approach:

$http.jsonp('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json').then(function(response) {
                $scope.zipCodes = response;
              });

Furthermore, I attempted to use AngularJS resource but it's giving me an undefined result:

var zipCodes = $resource("http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json",
            { callback: "JSON_CALLBACK" },
            { get: { method: "JSONP" }}
            );
        zipCodes.get({}, function(zipCode){
            console.debug(zipCode.PostalCode);
        });
        console.debug(zipCodes.get());
        $scope.zipCodes = zipCodes.get().results;

Answer №1

Ensure to utilize response.data when using the .then method, as it contains four parameters within the response object - specifically data, status, headers, and config

$scope.zipCodes = response.data;

Another Option

An alternative approach is to utilize either the success or error function

$http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=485a35b6b9544134b70af52867292071&d=20&pt=PostalCode&format=json')
.success(function(data, status, headers, config) {
     $scope.zipCodes = data;
})
.error(function(error, status, headers, config) {
     console.log(status);
     console.log("Error occurred");
});

Answer №2

Why is the filter json included there? When you visit the URL, you will receive an array of elements. Give it a try by printing:

<pre>zipCodes {{zipCodes}}</pre>

After that, if you want to display anything else, you can iterate over it using ng-repeat and customize the display as required.

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

Unveiling the magic of Vue Composition API: Leveraging props in the <script setup> tag

I'm currently working on creating a component that takes a title text and a tag as properties to display the title in the corresponding h1, h2, etc. tag. This is my first time using the sweet <script setup> method, but I've encountered a pr ...

Suggestions for updating the 'begin' and 'finish' variables transmitted through ajax on fullcalendar?

Shown below is the URL to request JSON data via Ajax: '/php/get-events.php?start=2015-05-31&end=2015-06-07&_=1433154089490'. This query will fetch JSON data from 2015-05-31 to 2015-06-07. However, I am looking to retrieve data over a ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...

Utilizing Angular's service for a dynamic typeahead feature

Whenever I try to utilize a service that returns a promise, the typeahead feature fails to work properly... You can view the error in this plunk. While using the first method (getLocation), everything runs smoothly... However, when attempting to use a ser ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Access WordNet using JavaScript

Currently developing a web application that involves NLP tasks. In my past projects, I have used the JWNL library in Java which has always served me well. I am curious to know if you have any advice on the most effective approach for querying the WordNet ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...

Retrieving JSON-formatted data from the database

I am working on a simple PHP script that fetches data from a database and formats it into JSON. Here is an example of how the output looks: [ { S.no: "1", News: "http://example.com/news/1.pdf", Date: "2022-01-01", news_desc: "Example News Article 1" ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

Executing functions from main component in tanstack table operations

One of the reusable React components I have is: "use client"; import { useState } from "react"; import { ColumnDef, flexRender, ColumnFiltersState, getFilteredRowModel, getCoreRowModel, getPaginationRowModel, ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

Having trouble pinpointing the element with protractor's binding locator

<div class="apiRequestDisplay ng-scope"> <pre class="ng-binding">GET</pre> <pre class="ng-binding">v1/securityprofiles/{securityProfileID} </pre> </div> I am trying to target the specific text within v1/secur ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

having difficulty with executing ajax post within a JavaScript function

While working on my project, I encountered a small issue. I am able to read the HTML image value and pass it to a JavaScript method successfully. However, when trying to pass this value via AJAX POST to the controller, an unexpected error occurs. The con ...

What is the best way to retrieve an object from a POST request using Angular AJAX calls in a NODEJS environment?

When the button is clicked, a method will be called. The code for this is as follows: .controller('templeDetailsList', function ($scope, $http, $ionicModal) { $scope.starclick = function(){ var newFav = [{ ...

Combining two items to create a fresh one based on specific criteria

I'm currently working on a project where I need to merge two groups of objects based on a specific condition. Let me illustrate with an example: Consider the following two groups of objects: const one = [{code: 'a'},{ code: 'b'}, ...

Unable to use the .focus() method on a Link component by utilizing references in React Router 4

I am currently working with the Link component in react-router (v4). I have successfully attached a ref to this component and can log the reference. However, when I try to use linkRef.current.focus(), I encounter the following error: linkRef.current.focu ...