How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly.

Although I have identified where the problem lies in my code, I am uncertain about what the correct syntax should be. Therefore, my query is regarding how I should define $scope.dogs to display the JSON data on the webpage. In the HTML, I have placed {{dogs}} within the 'mainCtrl' controller.

Below is the snippet from the JS file:

const app = angular.module('dogBreedApp', []);

app.controller('mainCtrl', function($scope) {
  $scope.dogs = $.ajax(settings).done(function (response) {
  });
});

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://dogdatabase-d31f.restdb.io/rest/dogs",
  "method": "GET",
  "headers": {
    "content-type": "application/json",
    "x-apikey": "xxxxxxxxxxxxxxxxxxxxxx",
    "cache-control": "no-cache"
  }
}
$.ajax(settings).done(function (response) {
console.log(response);
});

The content for the settings variable along with the ajax functionality was directly taken from the restdb.io service, which is the source of the JSON data. It successfully logs the JSON data without any issues.

Being new to development, I anticipate that the solution might be relatively straightforward.

Thank you!

Answer №1

If you are utilizing AngularJS, I suggest using Angular's AJAX methods over jQuery's. One approach to implementing this is by placing the $http call within a service, allowing you to return the promise and manage its resolution in your controller. In cases where you are using the controllerAs syntax, it is important to store this in a local variable as inside the promise resolution, this will refer to the promise rather than the controller itself. For better formatting of the output in HTML, the json filter can be used to display the data with line breaks and indents.

angular.module('app', [])
  .service('dogsService', function($http) {
    var service = {};
    service.getDogs = function() {
      return $http.get('https://dogdatabase-d31f.restdb.io/rest/dogs', {headers: {
        'x-apikey': 'xxxxxxxxxxxxxxxxxxxxxx'
        }
      }).then(response => response.data);
    };
    return service;
  })
  .controller('ctrl', function(dogsService) {
    var _this = this;
    this.dogs = [];
    dogsService.getDogs().then((data) => {
      _this.dogs = data;
    }).catch((error) => {
      console.error(error);
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as $ctrl">
  <pre>{{$ctrl.dogs | json}}</pre>
</div>

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

Troubleshooting: AngularJS directive not functioning properly with $http request

This is the structure of my code: View: <form action="./?app,signin" method="post" id="signinform" name="signinform" novalidate vibrating loginform> (...) </form> JavaScript: angular.module('loginApp', []) .directive('log ...

Managing Datatable with a dynamic header and data is an essential skill that can greatly enhance

I am struggling to handle the Datatable for different header column names with data from my controller. I am passing table headers column name and table data value from my controller. Although I am able to access columns in json within the drawCallback f ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

initial cookie value not established in angular js

I need help passing a cookie value from one UI to another page. The specific cookie value I want to retrieve is the user's username, for example: Nithya When I log in to the home page, the cookie value appears empty until I refresh the page. Is the ...

Guide on sending PHP array to jQuery using AJAX with JSON?

Currently, I am working on building a calculator that utilizes ajax in jQuery to send values to a PHP file and then receive the results back in jQuery. While I have accomplished getting one result returned successfully, my goal is to have two separate resu ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

How can an Angular 2 component detect a change in the URL?

My Angular 2 component subscribes to a service based on the URL hash without calling any subcomponents. I am wondering if I should use Route or Location for this scenario, and how can I listen for and react to a pop state event? ...

Manipulating the size of a square using gestures and touch events for seamless resizing

I am trying to center a blue square with the ID #square both vertically and horizontally in my viewport on my iOS device... <div id="square"></div> #square { width:100px; height:100px; background:blue; margin:0 auto; } I want ...

Blooming into Action - Transforming JSON Data into a Vibrant Web Page

I have implemented a basic service using Spring framework: @RequestMapping(value = "/list", method = RequestMethod.GET) public @ResponseBody List<Person> eventList() throws ParseException { return personDAOImpl.list(); } Upon accessing the corr ...

Converting a Pandas Dataframe into JSON: A Step-by-Step Guide

Hello everyone! I have a Pandas Dataframe called data1 that I need to convert into a specific JSON format string called data2. How can I achieve this? data1 = pd.DataFrame( { "country": ["USA", "USA", "USA&qu ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page: <input type="checkbox" id="autoload" class="aut ...

Adjusting the border-right size based on scroll position

Apologies if this question seems trivial, but I am completely new to coding in HTML and JavaScript. I understand that I can make some changes based on scroll position, but right now I'm a little confused. I want to increase the height of a box as the ...

Tips on sending an Ajax POST request to execute a PHP file

//The code below is found in the inserirPF.js file function add(){ var method = 'AddPerson'; $.ajax({ url: "../class/dao/InserirPFDao.class.php", type: 'POST', data: {Method:method, NAME_:NAME, EMAIL_:EMAIL, PASS ...

Error message: A circular structure is being converted to JSON in Node.js, resulting in

So here is the error message in full TypeError: Converting circular structure to JSON --> starting at object with constructor 'Socket' | property 'parser' -> object with constructor 'HTTPParser' --- prope ...

Designing a personalized look for a property with Styled-System

Styled-System offers various props related to css grid: I have a suggestion for a new prop, gridWrap. My idea is to allow users to adjust the auto-fit value using the gridWrap prop. Here's the base CSS code: grid-template-columns: repeat(auto-fit, mi ...

What is the process for opening and populating dialogs from dynamically mapped cards?

I have a unique array of JSON data that is connected to Material-UI (MUI) cards. Each card features a button that triggers a dialog to open. When clicking the button on a card, I aim to pass the specific value of GroupName into the dialog. In my case, ther ...

Guide to handling HTTP request parsing in Express/NodeJs when the content type is missing, by setting a default content type

Is it possible to retrieve POST data in an express request when the bodyParser does not work? var server = express(); server.use(express.bodyParser()); server.post('/api/v1', function(req, resp) { var body = req.body; //if request header doe ...

JavaScript having trouble parsing JSON, despite Chrome console being able to parse it flawlessly

I've hit a roadblock while attempting to retrieve coordinates from a database for the Google Maps API in order to create a polygon. First, I fetch my data from the database using Laravel Framework: MapController - public function getallmapcoords(re ...

Tips for extracting values from a JSON object

I have been attempting to retrieve the value from an array without success. Here is the current array: [{0: {value: 2, label: "ARKANSAS"}}] When I try to use JSON.parse(object), I encounter the error VM20617: 1 Uncaught SyntaxError: Unexpected ...