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

Having difficulty accessing data in a JavaScript file within Odoo 9 platform

I have attempted to extract HTML content from JavaScript declared in my module. However, when I try to retrieve content by class name, all I can access is the header contents and not the kanban view. openerp.my_module = function(instance) { var heade ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

Converting data types when transferring a JavaScript variable to a PHP variable

I have a boolean value stored in a JavaScript variable var value=true; alert(typeof(value)); //Output: boolean I need to pass this variable to a PHP file through AJAX $.ajax({ type: 'POST', data: {value:value}, url: 'ajax.php& ...

How can one restrict the display of fields in the Meteor aldeed tabular package?

How can I restrict certain data from being displayed in an aldeed tabular datatable? For instance, if my collection includes attributes A, B, C, D and attribute C contains sensitive information that should not be published, is there a way to prevent it fro ...

Is there a way to prompt WebAPI to receive a complicated object as its argument for a DELETE HTTP request without relying on C# attributes?

Currently, my server is utilizing C#/WebAPI while the client side is using AngularJS. I am faced with a dilemma when it comes to formatting an HTTP DELETE request without specifying attributes in C#. Specifically, I am struggling with how to handle a meth ...

Incorporating a timeline of activities using Angular

Transitioning from jQuery to Angular, I'm having trouble figuring out how to approach this. Here is the structure of my table: <div class="col-xs-10"> <table> <thead> <tr> <th>A</th> <th>B</th&g ...

Tips on recycling JavaScript files for a node.js API

I'm currently using a collection of JS files for a node.js server-side API. Here are the files: CommonHandler.js Lib1.js Lib2.js Lib3.js Now, I want to reuse these JS files within an ASP.NET application. What's the best way to bundle these f ...

"Using only JavaScript to target and manipulate child elements within the

I'm currently transitioning from using jQuery to pure JavaScript, and I've just started but am encountering difficulties. Specifically, I am unsure how to select child elements in the DOM. <div class="row-button"> <input type="submi ...

I am facing an issue where Bootstrap button classes are duplicating when I inspect the code. How can I resolve this

Can anyone help me with an issue I am facing with a Bootstrap button? Despite using only the btn btn-default classes, when inspecting it in Chrome, multiple classes are being displayed on the button. I'm unable to figure out why this is happening and ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Firebug reveals the JSON data being sent through AJAX requests, whereas PHP indicates that the $_POST variable is empty

I am currently working on my first AJAX transaction and, unfortunately, I have hit a roadblock towards the end. I am attempting to send a JSON string via AJAX to a php page called verify.php. However, when I try to retrieve this data, it appears that $_P ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...

The background image causes the scrollbar to vanish

As a beginner, I am in the process of creating a web page that features a consistent background image. However, I have encountered an issue where the scroll bar does not appear on a specific page called "family details" due to the background image. I atte ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

How can I retrieve the position of a div or an image within a div (specifically the top and left coordinates) and incorporate these values into CSS?

I'm currently working on a website that is dynamic and utilizes bootstrap. I am looking to incorporate an animation where the dynamic thumbnails in the col-md-4 div zoom to 100% when clicked, appearing at the center of the container. I am struggling ...

Steps for extracting a single string from a cURL response

I have been using cURL to access information from a repo via the Github API. However, I am struggling to extract only the name of the repository from the response data. How can I retrieve just a single string from the response and output it with an echo st ...

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...