Trouble retrieving data from an array in Angular locally

No matter how hard I tried, fetching data from MySQL, H2, and Derby databases seemed impossible. Following the instructions on w3schools website didn't yield any results. However, a light bulb went off in my head and I decided to give the Array Function a shot. I then tested it with a Java JSP page embedded in my AngularJS page.

Take a look at the index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <style>
            table, th , td  {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
            }
            table tr:nth-child(odd) {
            background-color: #f1f1f1;
            }
            table tr:nth-child(even) {
            background-color: #ffffff;
            }
        </style>
        <script src="angular.min.js"></script>
    </head>
    <body>
        <div ng-app="myApp" ng-controller="customersCtrl">
            <table>
                <tr ng-repeat="x in names">
                    <td>{{ x.Name }}</td>
                </tr>
            </table>
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.controller('customersCtrl', function($scope, $http) {
                $http.get("http://localhost:8080/pavanjsp/jsondata.jsp")
               .then(function (response) {$scope.names = response.data.records;});
            });
        </script>
    </body>
</html>

This is the jsondata.jsp file used:

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>

<html>
    <head>
        <title>JSON Data</title>
        <link rel="stylesheet" href="dist/css/bootstrap.css" />
    </head>
    <body>
        <div class="container-fluid">
            <%
                String[] names = { "Alfreds Futterkiste", "B's Beverages", "Berglunds snabbköp", "Blondel père et fils", "Bólido Comidas preparadas", "Bon app'", "Comércio Mineiro" };
                response.addHeader("Access-Control-Allow-Origin", "*");
            %>
            <%
                out.print("{ \"records\":[ ");
                for(int i = 0; i < names.length; i++)
                {
                    if(i == (names.length - 1))
                        out.print("{\"Name\":\"" + names[i] + "\"}");
                    else
                        out.print("{\"Name\":\"" + names[i] + "\"}, ");
                }
                out.print(" ] }");
            %>
        </div>
    </body>
</html>

I even attempted renaming the index.html as index.jsp and deploying it on Tomcat, but to no avail. PHP code was also experimented with without success.

If anyone has insights or suggestions, please do share!

Answer №1

After some research and trial and error, I was able to find a solution to my problem. Special thanks to cyan for the assistance provided. The issue stemmed from the response handling, and the revised code is shown below:

jsaondata.jsp(hosted on tomcat)

<%@ page contentType="application/json; charset=iso-8859-1" language="java" %>

<%
    String[] names = { "Alfreds Futterkiste", "B's Beverages", "Berglunds snabbköp", "Blondel père et fils", "Bólido Comidas preparadas", "Bon app'", "Comércio Mineiro" };
    response.addHeader("Access-Control-Allow-Origin", "*");
%>
<%
    out.write("{ \"records\":[ ");
    for(int i = 0; i < names.length; i++)
    {
        if(i == (names.length - 1))
            out.write("{\"Name\":\"" + names[i] + "\"}");
        else
            out.write("{\"Name\":\"" + names[i] + "\"}, ");
    }
    out.write(" ] }");
%>

angulardata.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table, th , td  {
  border: 1px solid grey;
  border-collapse: collapse;
  padding: 5px;
}
table tr:nth-child(odd) {
  background-color: #f1f1f1;
}
table tr:nth-child(even) {
  background-color: #ffffff;
}
</style>
<script src="angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/pavanjsp/jsondata.jsp")
   .then(function (response) {$scope.names = response.data.records;});
});
</script>

</body>
</html>

Answer №2

Have you tried adjusting the code like this:

$scope.names = JSON.parse(response.data).records;

If that doesn't solve the issue, make sure to check if you are receiving valid JSON from the server. You can do this by opening your browser's developer tools (usually accessed with F12) and checking the network tab.

Once you have located the response, copy it and paste it into a JSON validation tool. If the JSON is valid, then there may be an issue within your Angular app, although everything appears to be in order.

Additionally, verify in the developer tools that CORS is properly configured for this call. An HTTP status of 200 indicates success.

You can also utilize the $log service for debugging purposes:

app.controller('customersCtrl', function($scope, $http,$log)

.then(function (response) {$log.debug('response',response);

I hope these suggestions prove helpful.

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

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Uploading Images with PHP and Showing Server-Side Errors in real-time on the webpage

I currently have a form that makes use of uploads.php. The code snippet is shown below: <?php include 'config/database.php'; $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $u ...

Symfony equivalent of Auth::attempt

Looking for a straightforward way to authenticate users in Symfony similar to Laravel's Auth::attempt(... method. My user entity already implements AdvancedUserInterface, and I've been reviewing the Symfony security documentation. I'm searc ...

Remove any errors as soon as the input field becomes valid

My current setup involves AngularJS with node.js. To handle errors, I have devised the following strategy: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Eff ...

When sending an AJAX request to a URL, can I verify in the PHP page whether it is a request or if the page has been accessed?

In order to enhance security measures, I need to prevent users from accessing or interacting with the php pages that will be utilized for ajax functionality. Is there a method available to determine if a page has been accessed through an ajax request or b ...

Ordering Products in a Unique WooCommerce Shopify Theme

I'm encountering an issue with a purchased theme. I require the theme to arrange items in ASC order by date, similar to how woocommerce does it: [recent_products per_page="12" columns="4" orderby="date" order="asc"] However, this particular theme re ...

Discover the power of AngularJS's ng-route feature for creating a dynamic and seamless one-page HTML template experience

I'm attempting to create a dynamic header using ng-repeat. Here's the initial code: <ul class="right"> <li><a href="#carousel">Home</a></li> <li><a href="#about-us">About Us</a></li> &l ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Implementing AJAX, PHP, and MYSQL to dynamically fill text boxes with data when an item is selected

How can I capture user input in a text box based on their selection of a place? I have attempted to achieve this functionality with the code below, but it's not working as expected. Can someone offer guidance on how to fix this issue? This is what I& ...

Transferring a variable value between functions using autocomplete and AJAX communication

I am facing difficulties with implementing autocomplete jQuery along with AJAX call. The issue arises when a user enters text in the input field, triggering an AJAX POST request to the controller which retrieves values from the database and sends them back ...

Switching to an Apache server from a node.js server

I have been working with react-webpack and running my project on node.js. However, I now need to incorporate some PHP files into the project due to new requirements. I am unsure of how to add PHP files to my project and transition from node.js to Xampp in ...

Bringing in Node Package in Angular

I decided to clone the Angular project from here: https://github.com/etherparty/explorer Now, I am looking to incorporate another module into it by following this link: https://github.com/miguelmota/ethereum-input-data-decoder However, when trying to uti ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Nobody exists in the realm of PHP curl

I'm trying to send a JSON array with cURL to a specific URL and retrieve the response body which should be a code. However, my issue is that I'm only getting a 1 (true) as the response. $array = [ "type"=>"send", "phone"=>"98910778 ...

Converting Curl Parameters into PHP-Curl

(I've encountered NUMEROUS variations of this question numerous times before, so I thought I'd create a thread with a somewhat comprehensive list of responses) ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

A guide to disabling daily checkboxes and retrieving the chosen values using Angular.js

Within a single table, I have incorporated a dynamic drop-down list that spans over 7 days. Additionally, I have implemented a "+" button that allows for the creation of additional rows dynamically for each day. Each row within the table features a checkb ...

Improving Angular factory's counter with socket.io integration

I am currently working on a solution to automatically update the number of incoming data. I have set up a system to listen for incoming messages and count them in a factory: angular.module('app') .factory('UpdateCounter', ['s ...

Using the JQuery Library, you can implement two submit buttons that either open in a new tab or submit

I am facing a situation where I have a FORM containing two submit buttons. My requirement is that when the first button is clicked, the form should submit on the same tab. On the other hand, if the second button is clicked, it should proceed to open a new ...

Changing dropdown values in PHP upon selection

When I try to send the value of a dropdown on change to a PHP script, I encounter an issue where both the form and status string are posted twice. One with the GET parameter set and the other without. I'm unable to figure out how to solve this problem ...