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

Is there a way to adjust the quantity individually, both increasing and decreasing as needed?

I am currently working on implementing a shopping cart feature using pure JS that allows users to increase and decrease the quantity of items. When the + or - button is clicked, both items in the shopping cart will be affected simultaneously if there are 2 ...

When sending Object Content to the Telegram API using HttpClient, the response code returns as 400

I'm currently developing a Telegram Bot to integrate with our own application. My initial approach was using the DHC Chrome extension, similar to RestClient extension, to test the data exchange between our application and the Telegram server. Moving o ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

Using JavaScript to reduce, group, and sum nested objects

I'm a third-year student working on my first internship project and struggling with organizing and aggregating data from a JSON object. The goal is to group the data by name, calculate total weight per name, and sum up the grades for each entry. I&apo ...

Utilizing ng-model in AngularJS to add data to an array in Mongoose and MongoDB

I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] ...

Switching camera view on mouse click with three.js

I am new to three.js and apologize if my question is a bit complex. I have set up my scene in three.js but now I want the camera's position to smoothly transition from point A to point B (which I will specify in my code). I plan on using Tween.js to ...

Preventing a Click Event on Child Element from Triggering the Parent's Click Event in jQuery

Can you help me figure out how to prevent a button from executing the onclick function of its parent div in this example? <div onclick="$('#extra-info').slideToggle();" class="card card-body item"> <div class="ro ...

Tips for enabling resize functionality on individual components one at a time

Check out my Codepen link for the resizable event While using Jquery UI resizable, everything is functioning correctly. However, I am now looking to have the resizable event activate one block at a time. When another block is clicked, the resizable event ...

The functionality of a radio button triggering a form submission to different pages is experiencing issues with Firefox

This piece of code is designed to submit a form when a radio button is clicked, and depending on which radio button is selected, the form action should change. While this code works fine in Chrome and Opera, it doesn't seem to function properly in Fir ...

Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time. Here is what I have: function animation() { document.getElementById('ExampleButton').className = &apo ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...

jQuery Rails breathes new life into live search input box

I'm new to jQuery and recently followed a tutorial on creating a live search bar. The functionality works well, but I noticed that with every character entered, the ajax request triggers and causes me to lose focus on the text box. This forces me to r ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

The video element in HTML5 is not showing up on Safari browsers, but it is functioning properly on Chrome

I have set up a video slider on my webpage. You can view the site The code is functioning perfectly on Chrome and iOS Safari, but there seems to be an issue on desktop browsers. When inspecting the page in Safari, the video elements are present in the HTM ...

Removing an embedded document from an array in MongoDB using Mongoose when the document's status is set to false

I am in desperate need of a solution for this mongoose-related issue. My tech stack includes Express, Mongoose, and GraphQL. To give you some context, I have two collections: users and groups. user { name: string, groupAsMember: [groups], status: bo ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Troubleshooting the issue with mocking API and creating a regular expression to match the dynamic part of a URL

I am struggling to create a mock for an API that includes dynamic parts in the URL. I attempted to use a regular expression, but it is not functioning as expected. The URL I am trying to mock is: https://example.com/programs/2fcce6e3-07ec-49a9-9146-fb84fb ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

A specialized authorization attribute that combines the name of the controller with the name of the action

My custom AuthorizeAttribute is functioning well, as shown in this post about handling session timeout in ajax calls. However, there is a challenge with the LogOn Action of the Account Controller in ASP.NET MVC. Upon logging on, it returns to the last page ...

"Calculating the total value of an array based on its individual elements

My API response includes committers to a git project, but some members are repeated because they share the same name with different email addresses. Example response: [ {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/emai ...