Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service:

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

init();

function init() {
    $scope.customers = customersService.getCustomers();
}

});

app.service('customersService', function ($http) {
this.getCustomers = function () {
    return customers;
};
// The issue lies here
$http.get("app/server/read.php")
    .success(function(data){
        var customers = data;
    });
});

In my PHP script, I have the following code:

$result = mysqli_query($con,"SELECT * FROM customers");
$return_arr = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rowArr = array(
    'id' => $row['id'],
    'firstName' => $row['firstname'],
    'lastName' => $row['lastname'],
    'address' => $row['address'],
    'city' => $row['city']
);

$return_arr[] = $rowArr;
}
echo json_encode($return_arr);

The JSON array returned by PHP looks like this:

[{"id":"36","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"37","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"38","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"39","firstName":"","lastName":"","address":"","city":""},{"id":"40","firstName":"asd","lastName":"asd","address":"","city":"asd"}]

I am struggling to assign this JSON object array to the variable customers dynamically after the successful response of the GET method.

Answer №1

To populate your $scope with data from a service, return the promise from the $http call in the service and use the .success callback to update the $scope property.

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

    init();

function init() {
    customersService.getCustomers().success(function(data){
        $scope.customers = data;
    });
}

});

app.service('customersService', function ($http) {
    this.getCustomers = function () {
        return $http.get("app/server/read.php");
    };
});

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

What to do when encountering a problem with HTML, CSS, and JS while loading a webpage from an SD card to a WebView

I am facing an issue while loading an HTML file from the SD card to a webview. The problem is that the CSS, images, and videos are not loading properly in the webview. Compatible with Android 4.4 KitKat and Chrome version Not compatible with versions belo ...

Troubleshooting scope evaluation in AngularJS within style tags on IE9 not functioning

My issue involves a div block with a style attribute that includes left:{{left}}px; and right:{{right}}px. Even though $scope.left and $scope.right are being updated, my item still doesn't move as expected. I have created a fiddle to demonstrate th ...

scope.$digest completes before triggering scope.$watch in Karma unit tests

I am interested in testing this specific directive: .directive('uniqueDirective', function () { return { restrict: 'A', scope: { uniqueDirective: '@', tooltip: '@', placement: '@&apo ...

Issue: The value of an object is not defined (evaluating '$scope.inputcode.password')

HTML Form: <form ng-submit="mylogin()"> <div class="list"> <label class="item item-input"> <span class="input-label">Username</span> <input type="text" ng-model="inputcode.username"> ...

Display the jQuery validation message in the final td cell of the table

JavaScript Animation Library rules:{ gender: { required: true }, }, messages:{ gender: { required: "Please indicate your gender" }, }, errorPlacement: function (error, element) { if (element.attr("type") == "radio") { ...

Issue with retrieving the value of a JavaScript dynamically generated object property

I'm currently working on a React Material-UI autocomplete component and facing challenges with accessing a Javascript Object property within a handleSelect function. Although I can retrieve the townname value using document.getElementById, I know thi ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

Issue with navigating using Ionic v1 $state.go not functioning as expected

Hi everyone, I'm new to posting here and I hope I am clear in my explanation. I am having trouble with getting $state.go to work in my project. Despite searching extensively, I haven't been able to find a solution yet. This technology seems great ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

Leveraging jQuery for fetching URLs from an RSS feed

Currently, I am experimenting with an rss feed and attempting to construct a template that will display the values retrieved from it. For now, my main focus is on confirming that I can access each value successfully. However, when executing the code below, ...

Obtain HTML tags from RSS CDATA section

Is there a way to extract HTML tags from a CDATA tag in an RSS feed? I have utilized a basic jQuery function to retrieve the JSON object from the RSS, below is my code: $.get("someURL", function(data) { console.log('InGet'); ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

Creating a well-formatted JSON string using Python

My system revolves around a C++ main component that serves as the core for a complex process. This core is responsible for running python scripts that carry out various tasks and then presenting them on an HTML-based Graphical User Interface. While this HT ...

Can you explain the distinction between ajaxComplete and beforesend when making an Ajax call with JavaScript?

Can you explain the usage of ajaxComplete and beforesend? What sets them apart from each other? Are there any alternative methods similar to success when making an Ajax call? ...

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

Parsing JSON using Gson with the same key but different values

This is an example of a JSON event: { "type":"record", "name":"Doc", "doc":"adoc", "fields":[ { "name":"id", "type":"string" }, { "name":"user_friends_count", "type":[ "int", "null" ...

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...