Having trouble making an AJAX request work in AngularJS?

Just dipped my toes into the world of Angular (only a few hours in). Managed to tweak the demo to get close to what I need, but hitting a roadblock with my AJAX request.

After trying a variety of fixes, one puts me in an endless loop (discovered that's just how Angular operates), while another solution doesn't seem to do anything at all.

Here's what I've got so far (attempted to slot the peopleController pretty much everywhere):

Controller:

app.controller('MainController', ['$scope','$http', function($scope,$http) {
    //$http is working in this

    var scrollItems = [];

    for (var i=1; i<=100; i++) {
        scrollItems.push('Item ' + i);
    }

    $scope.scrollItems = scrollItems;    


    function peopleController($scope,$http){
        // Simple GET request example :
        $http.get('/public/ajax.php').
        success(function(data, status, headers, config) {
            console.log("worked");
            // this callback will be called asynchronously
            // when the response is available
            scope.people = data;
            }).error(function(data, status, headers, config) {
                console.log("fail");          
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
     }          
}]);

HTML:

<div ng-controller="peopleController">
     {{people}}
</div>

Encountering this error though:

Error: [ng:areq] http://errors.angularjs.org/1.3.0/ng/areq?p0=peopleController&p1=not%20aNaNunction%2C%20got%20undefined
    at Error (native)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:6:416
    at Mb (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:19:510)
    at nb (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:20:78)
    at $get (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:74:494)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:56:415
    at r (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:7:408)
    at M (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:56:281)
    at g (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:51:201)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js:50:309

Hoping to find some guidance here :)

Tried following other solutions as well

Answer №1

Make sure to match the controller name in both your HTML and JavaScript files. If it's 'peopleController' in your HTML file, name it 'peopleController' in the controller instead of 'MainController'.

Then modify the following line:

function peopleController($scope,$http){

to:

function peopleController(){

Remember to use dependency injection in the controller function, not on the contained functions. The contained functions already have access to $something because they are within the scope of the controller function.

Answer №2

Ensure that your view is connected to the specified controller, which in this case is MainController:

<div ng-controller="MainController">
        {{people}}
</div>

Within the controller, initialize the people variable as an empty array and bind it to the $scope object. Remove any unnecessary parameters from the peopleController function and trigger the request. Note: make sure to refer to $scope instead of just scope in the success handler.

$scope.people = [];

peopleController(); //initiate the ajax request

function peopleController(){ //remove unnecessary parameters
        // Example of a simple GET request:
        $http.get('/public/ajax.php').
          success(function(data, status, headers, config) {
          console.log("worked");
            // This callback will be executed asynchronously
            // once the response is received
            $scope.people = data; //$scope instead of scope
      }).
      error(function(data, status, headers, config) {
      console.log("fail");        
        // Executed asynchronously in case of an error or
        // if the server responds with an error status.
      });
    }     

The name peopleController() can be misleading since its main purpose is to fetch data. It might be more appropriate to rename it to getPeople().

Answer №3

To create a separate controller named peopleController, you must define it individually like so:

app.controller('MainController', ['$scope','$http', function($scope,$http) {
      //$http functionality is operational within this controller

      var scrollItems = [];

      for (var i=1; i<=100; i++) {
        scrollItems.push('Item ' + i);
      }

      $scope.scrollItems = scrollItems;    



 }]);

 app.controller('peopleController', ['$scope','$http', function ($scope,$http){
        // Demonstrating a simple GET request example:
        $http.get('/public/ajax.php').
          success(function(data, status, headers, config) {
          console.log("Request successful");
            // This callback will be executed asynchronously
            // upon receiving the response
            $scope.people = data;
          }).
          error(function(data, status, headers, config) {
          console.log("Request failed");        
            // Executed asynchronously if an error occurs
            // or server responds with an error status
          });
        } 
 }]);      

Answer №4

To avoid conflicts, it is recommended to eliminate the usage of $scope and $http within the peopleController function.

Additionally, consider using ng-controller='MainController' instead of ng-controller='peopleController'.

It would be advisable to rename peopleController to getPeople if you intend for it to be a function rather than a controller.

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

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

AngularJS: Utilizing ng-click in ui-select choices

Trying to incorporate an add button within the options, but facing a challenge where ng-click triggers without selecting the option. <ui-select ng-model="datactrl.newservice.selected" theme="selectize" ng-disabled="disabled" style="width: 100%;"> ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

Load styles in Nuxt asynchronously to improve performance

Is there a way to load styles asynchronously on the website or insert them in the footer? I am currently using Nuxt version 2.0.0 Here's what I have tried so far: Adding a plugin in webpack called async-stylesheet-webpack-plugin. However, this res ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

Struggling to receive a successful reply from a web service

Currently in the process of developing a web frontend for a web service, I am utilizing jQuery 1.5.1 as my JS framework and Firebug for debugging purposes. To ensure functionality, I tested the web service using the Firefox Extension "REST Client", which ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

What kind of output should a Server Side Component generate?

Recently, I decided to incorporate the NextPage type from Next.js into my component writing routine after hearing it's a beneficial practice. However, I discovered that it only functions properly with client-side components. When attempting to utilize ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

Sending a POST request results in both the execution of the THEN and CATCH

I am encountering a strange issue with my submit function, which is used to save an article. Despite receiving a success response code of 200 in the browser, both the 'then' success branch and the 'catch' error branch are triggered simu ...

during implementation of ng-repeat directive with JSON dataset

When I receive JSON data and attempt to display it using the ng-repeat directive, I encounter an error ng-dupes error <table> <tr ng-repeat="emp in empArr"> <td>{{emp.empcode}}</td> <td>{{emp.empName}}< ...

Tutorial on Removing and Re-Adding HTML Elements

Currently, I am utilizing Jquery to temporarily remove an element from the DOM. This specific element consists of an HTML5 video element. However, upon re-adding this element back into the DOM, the video is unable to play and the element appears as blank o ...

Despite being used within useEffect with await, asynchronous function fails to wait for results

In my component, I am utilizing a cookie value to determine which component or div block to display. The functionality works correctly in the end, but there is a brief moment where it seems like the cookie value is not being checked yet. During this short ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

Having trouble with my AngularJS directive (possibly)?

Check out my main JavaScript file: var app = angular.module('app', [ 'ngRoute' ]); app.config(['$routeProvider', function($routeProvider) { $routeProvider .when("/calendar", { templateUrl: "views ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

By utilizing .focus() in iOS8, the virtual keyboard will be displayed and the page will automatically scroll upon touch

In the era before iOS8, when utilizing the Javascript .focus() method on an input element, it seemed as though nothing happened - the virtual keyboard did not make an appearance. However, with the latest iOS 8 update, executing the .focus() method initiall ...

Calculate the duration in seconds using the console

Is it possible to display the time of an action in seconds instead of milliseconds using console.time? Below is my code: console.log('start load cache'); console.time('cache load ok executed in') // loading from mongo console.timeEnd( ...

Approach to retrieving data with Nodejs API

Currently, I am working on a project with Node.js and using Express.js. My goal is to retrieve data from a MySQL database, but I encountered the following error: "await is only valid for async function" How can I resolve this issue? Below is the ...

What is the process for sending a REST request in my specific situation?

I’m currently going through a RESTFUL API documentation where one of the PUT methods necessitates sending a request body. The specified documentation includes: PUT /api/v1.2/product/{id} along with an example request body like this: { "name" : "Toy ...