Having trouble showing the JSON data on the HTML page

I have successfully managed to use $http.get in my script to retrieve JSON data, which I receive in Object Form. However, I am facing issues when trying to access the values in the array.

https://i.sstatic.net/skKjq.png

Below is a snippet of my AppCtrl portion (AngularJS)

app.controller('AppCtrl', function($scope,$http) {


$scope.data = [];
$scope.submit = function() {

var link = 'http://www.mywebsite.com/api.asp';
$http.get(link).then(function(response) {
    $scope.data = response.data;
    console.log($scope.data);
});
};
});

And this is the HTML section:

<form ng-submit="submit()">
      <input class="button button-block button-positive" type="submit" name="submit" value="Submit To Server">
    </form>
    <div class="card">
        <li ng-repeat="userdata in data">
          Username : {{userdata.username}}
          Age : {{userdata.age}}
        </li>
    </div>

Although I have retrieved the JSON data, I am having difficulty accessing it properly. I suspect that I might not be calling it correctly. Any guidance would be appreciated!

UPDATE: When I run console.log($scope.data), I see:

"0 925121 log [object Object]"

I tried using JSON.stringify on the response.data and now I get a different console.log result along with a new error message.

The console.log displays the JSON information as follows:

{"data":[{"ID":1,"age":"24","username":"hidir"},{"ID":2,"age":"51","username":"ibrahim"}]}

However, I encountered an error indicating duplicate values in the array, even though it doesn't seem like there are any duplicates:

"Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: userdata in data, Duplicate key: string:a, Duplicate value: a
http://errors.angularjs.org/1.5.3/ngRepeat/dupes?p0=userdata%20in%20data&p1=string%3Aa&p2=a

"

Answer №1

Would you be willing to give this a shot?

app.controller('AppCtrl', function($scope,$http) {
    $scope.name = null;
    $scope.submit = function() {
        var link = 'http://www.mywebsite.com/api.asp';
        $http.get(link).then(function(response) {
            $scope.data = response.data;
            if(!$scope.$$phase) {
                //$digest or $apply
                $scope.$apply();
            }
        });
    };
});

Answer №2

Consider incorporating a success function after making the $http call as shown:

$http.get(link).success(function(response) {
    console.log(response);
});
}; 

Answer №3

Consider utilizing JSON.stringify(response.data);

Answer №4

Here is an example of using the $http service to make a GET request and handle the response:

$http({
  url : link,
  method : "GET",
  headers: {
      'Content-Type': 'applcation/json'
     }
}).then(function(response) {
    console.log(response);
    $scope.data = angular.fromJson(response.data);
    console.log($scope.data);
});

Answer №5

Thanks to @Abhinav's solution, I was able to identify the issue with my JSON structure. It would be beneficial if someone could provide a more detailed explanation for future reference, as I lack the expertise to do so.

*Initial JSON Structure that caused issues

{"data":[{"ID":1,"age":"24","username":"hidir"},{"ID":2,"age":"51","username":"ibrahim"}]}

With the above code, it only functions correctly when accessed with {{userdata[0].username}}. Utilizing the ng-repeat directive with this arrangement will result in failure.

Correct Array Format (compatible with Ionic)

[{"ID":1,"age":"24","username":"hidir"},{"ID":2,"age":"51","username":"ibrahim"}]

The ng-repeat directive operates smoothly with the second format.

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

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

What is the best approach to restructuring this code with an excessive number of $routeProvider routes in a single file?

After researching how to effectively wire up Angular with Express + Node, I stumbled upon a helpful article. One key takeaway was the ability to serve Angular templates from the same directory as views using the line of code: app.set('views', _ ...

Using Java Reflection to Retrieve the Names of all Instance Variables within a Class

I am currently working on developing an Android application that involves binding a JSON object to a domain entity. Each domain entity has different instance variables, and I need a method that can efficiently handle the binding process. Here is what I hav ...

Having trouble with the installation of nodemon globally on macOS Mojave?

When using the Visual Studio Code terminal, I ran the following command: npm install -g nodemon The output in the terminal showed: npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! syscall access n ...

Utilizing the bufferGeometry setFromPoints function in conjunction with react-three-fiber

Exploring the functionality of the toLinePath function: const toLinePath = (arrayOfPoints, color = 0x000000) => { const path = new THREE.Path(); const firstPoint = arrayOfPoints[0]; path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z); arrayO ...

What is the process for storing a loaded model in three.js?

Working on a video game, I am encountering memory issues. Specifically, when loading 8 object models, I find that I am repeating them throughout the game map. This results in me having to load the same model multiple times in different locations on the map ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

What encoding does Algolia utilize to determine the size of a JSON entry - ASCII or UTF-8?

The FAQ document from Algolia states that the maximum size of an entry should be a minified JSON size of 10KB. However, it does not specify whether the JSON string should be ASCII or UTF-8 encoded, which makes it challenging to accurately calculate the siz ...

Utilizing a dynamic variable to define the URL in a getJSON request with jQuery

I'm currently working on a weather app using jQuery. One issue I've come across is with my getJSON function - I want to utilize a variable that I created with the current latitude and longitude coordinates. The openweathermap API key loads the JS ...

Removing an element from an array in PHP results in adding a key to objects

When extracting data from a json feed, I specifically require four objects located at $json['content']['locations']['location']['cams']['cam']['snow']['wi']. Despite there being 5 objec ...

Having trouble with npm and unable to find a solution that works. Any suggestions on how to fix it?

I've been working on a JavaScript project that requires me to import a library, but I keep running into errors with npm every time I try to use it. Here is the error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What is the best way to transform an array of string values into numeric values for a Mongoose schema that includes several numeric fields?

Having an issue with a MongoDB collection named 'sold' that contains both string and numeric fields. const soldSchema = new Schema( { sku: String, hsn: String, qty: Number, article: String, mrp: Number, disc: Number, ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Exploring the functionality of the JavaScript switch statement across various condition scenarios

switch (true) { case (angle<20): console.log("case1") break; case (angle<70): console.log("case2") break; case (angle< ...

Saving a variable within a for loop in JavaScript

Hey everyone, I could really use your help right now. Here's the code block I'm struggling with: function readyToSubmit(answerPack, answerArr, len) { for (var i = 0; i < answerArr.length; i++) { var questionId = answerArr[i].id; con ...

Encountering an issue when implementing a conditional check within the .map() function utilizing ES6 syntax

I'm struggling to assign only the object that contains an iban value to the list in the code snippet below. I haven't been able to fix this issue on my own and would appreciate some assistance. This.ibanList = this.data.map( (value, in ...

Issue with vue-apollo package causing GraphQL query not to display on the frontend

Currently, I am expanding my knowledge of GraphQL and working on a project where I aim to display queries in the front end. To achieve this, I have incorporated the package GitHub - Akryum/vue-apollo: ...

Using C# to Deserialize Json Data with Json.Net

I've been attempting to work with a JSON structure using Json.NET, but so far, I haven't had any success. { "Sample": [ { "content": "blah...", "Identifier": 6, "Timestamp": "2013-04-13T00:00:00" }, { "conte ...

Encountering an error with NodeJs, AngularJs, and Mongoose: TypeError - Object.keys invoked on a non-object leading to Function.keys (native)

Here is the code snippet related to the issue: server.js file: app.post('/user', function(req,res){ console.log(req.body); var user = mongoose.Schema('User',req.body); user.save(function(err,user){ if(err) console.l ...

Unable to retrieve image data from Ajax to Java, but successful in receiving the image bytes

Currently, I am in the process of sending an image to the server side. The base64 formatted image is received from a third party and for bandwidth optimization reasons, I intend to send this data in binary form (decoding is essential). It is important that ...