Showing JSON information in an Angular application

Upon page load, I am encountering an issue with retrieving and storing JSON data objects in Angular scope for use on my page and in my controller. When attempting to access the value, I receive the error message:

angular.js:11655 ReferenceError: data is not defined

The specific values I am looking to store include:

c_name

max_slots

base_image

In summary, what I require is:

I need these array objects stored as scope variables so that they can be utilized within my HTML code and elsewhere in my JavaScript controller.

Here is a snippet of my JSON data:

{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
...

Below is the excerpt from my JavaScript code where I attempt to retrieve the data:

My JavaScript

$scope.GetData = function () {
    $http({
        url: "http://www.site.co.uk/one/two/getdata",
            method: "POST",
            date: {},
            headers: {'Content-Type': 'application/json'}
    }).then(function (response) {
        // success
        console.log('you have received the data ');
        console.log(response);
        // $scope.base_image = response.base_image; $scope.c_name = response.c_name;
        $scope.c_name = data.c_name;
        $scope.max_slots = data.max_slots;
        $scope.slot_image = data.slots.base_image;
        console.log($scope.c_name);
    }, function (response) {
        // failed
        console.log('failed getting campaigns goo back to log in page.');
        console.log(response);
    });
};

$scope.GetData();

This results in the following output when logging the data received:

you have received the data

{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
...

Additionally, here is a screenshot for reference:

https://i.stack.imgur.com/4MG3m.png

Answer №1

It seems like you need help with printing JSON data, so I'm here to provide a solution. If my answer doesn't meet your expectations, please feel free to clarify your question.

   $scope.FetchData = function () {
    $http({
        url: "http://www.example.com/api/fetchdata",
        method: "POST",
        data: {},
        headers: {'Content-Type': 'application/json'}
    }).then(function (response) {
        // success
        console.log('Data has been retrieved successfully');
        console.log(response); // if the response data is in JSON format
        console.log(angular.toJson(response)); // if the response data is in JSON format
        $scope.categoryName = response.category_name;
        $scope.maxCategories = response.max_categories;
        $scope.imageUrl = response.images.base_url;
        console.log($scope.categoryName);

    }, function (response) {
        // error
        console.log('Failed to retrieve data. Redirecting to the login page.');
        console.log(response);
    });
};

$scope.FetchData();

Answer №2

    $scope.FetchData = function () {
    $http({
        url: "http://www.website.com/endpoint",
        method: "POST",
        data: {},
        headers: {'Content-Type': 'application/json'}
    }).then(function (response) {
        // success
        var result = JSON.parse(response);
        console.log('Data received successfully.');
        console.log(result);
        $scope.campaign_name = result.c_name;
        $scope.max_slots = result.max_slots;
        $scope.slot_image = result.slots.base_image;
        console.log($scope.campaign_name);
    }, function (response) {
        // failed
        console.log('Failed to retrieve data, please log in again.');
        console.log(response);
    });
};

$scope.FetchData();

Replacing response with result should resolve the problem.

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

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

HTML Canvas resizing challenge

My goal is to resize the canvas to fit inside its parent div within a Bootstrap grid, but I'm running into an issue where the canvas keeps expanding to 2000px x 2000px. Despite successfully resizing based on console.log outputs showing the same dimens ...

Activate Pop-up for a single instance on BigCommerce

After researching and adding my own code, I am still struggling to get this question answered correctly. Here are the key points I am trying to achieve: 1. Automatically open a popup when the homepage loads. 2. Ensure that the popup is centered on all brow ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

The local database is not receiving any values

Retrieving data from a JSON URL on the server and saving it to a local database is causing an error. The process involves fetching a JSON array, which appears in the Logcat messages, but encounters issues when attempting to store the values in the local da ...

Ways to retrieve child state in React?

After creating my own form component with a render() method that looks like this: render() { return ( <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}> {this.props.children} </form> ) } I enabled ...

I am trying to display an element upon hovering using Jquery, but unfortunately, despite recognizing the event, it refuses to function as expected

I've been searching for a solution to show a submenu on hover by removing the hidden class that is hiding it. Despite trying various approaches, including using CSS and JavaScript, I haven't been able to make it work. Here is the code snippet I h ...

Tips on obtaining the JSON format of an object containing an array variable

In my class, I have three variables including an array. I created a method specifically for use with json_encode(). public function getJSONString(){ return [ 'id' => $this->id, 'name' => $this->name, ...

Tips for retrieving the values of both a checkbox and radio button in AngularJS

Hello, I have created MY PLUNKER I have a condition in my JSON where if the minimum value of the ingredients is equal to one, it will change to a radio button. If it's greater than one, it will change to a checkbox. To display as a radio button: ng ...

Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component. Here is the filter method I am trying to use: filterHotels:function(){ var thisHotels = this.hotelRoomArr; console.log(this.hotelRoomArr['107572']['rooms ...

Animation showing on the progress bar is not correctly halted

I am encountering a problem with handling an animation of a progress bar in my code. The issue arises when I pause the animation, as it seems to slightly backtrack instead of pausing at the correct position upon clicking a button. Can someone help identify ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Using Powershell to extract values from a nested array within an object in JSON

I'm trying to extract specific values from a JSON Array that is nested inside a JSON object: Unfortunately, using | formatFrom-JSON only returns the first line of data. I'm curious about how I can work around this limitation and retrieve just t ...

Utilizing hidden types for radio button validation in AngularJS: A step-by-step guide

<input type="hidden" value="{{r.radioname}}" name="{{field.Name}}" ng-model="inputfield[field.Name][r.radioname]" required> <input type="radio" id="radio_{{$index}}" value="{{r.radioname}}" name="{{field.Name}}" ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...

Learn how to implement a conditional class binding in Vue 3, and discover how to apply additional classes when a specific condition is met

As a newcomer to Vue.js 3, I am wondering how to implement a conditional class binding in Vue 3. Specifically, I would like to achieve the following logic: if router.path != '/', then add the class 'nav-bar-two'; otherwise, do not apply ...

Error encountered: WebGL Type error in Three.js

Currently working on a small music visualizer project using WebGL and Three.js with the help of the ThreeAudio.js library. Everything seems to be running smoothly, but I've encountered an error that I'm keen on resolving: "Uncaught Type Error: T ...

Tips for creating basic Jasmine and Karma tests for an Angular application to add an object to an array of objects

I have developed a basic Angular project for managing employee data and I'm looking to test the addProduct function. Can someone guide me on how to write a test case for this scenario? I am not using a service, just a simple push operation. Any assist ...

When working with AngularJS child routes, it is common for them to always redirect to the

My routing configuration is causing an issue where accessing a child route always redirects to the /login page instead of the intended route. Here is how my routing is set up: $stateProvider .state('login', { url: '/login', ...

Alter the hue within Google Chart

I'm working on customizing a Google Bar Chart with Material design and running into an issue with changing the background color. I've tried using backgroundColor and fill identifiers in the options, but the inner area of the chart where the data ...