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

Cordova Geolocation now displaying incorrect latitude and longitude values as NAN

Recently starting out with javascript and Cordova, I decided to develop a basic GPS app in Visual Studio 2015. The goal was simple: get my current position by clicking on the "CURRENT POSITION" button. Testing it in Firefox yielded positive results. Howev ...

Creating a bar chart in Chart JS using an array of data objects

I need to create a unique visualization using a bar chart where each bar represents a user or student. Each bar will have an xAxis label displaying the student's name. The code below is a VueJS computed property named chartData For my bar chart data ...

In Firefox, using the new Date function within a string does not function as expected

Why does the last log in the code snippet below not work in Firefox? (function() { String.prototype.toDate = function() { return new Date(this); }; console.log(Date.parse("2012-01-31")); console.log(new Date("2012-01-31")); c ...

Having trouble retrieving POST data with NodeJS/Express and an HTML form?

I have encountered an issue in my application where I am unable to extract the posted data from req after performing an action pointing to a nodejs endpoint. Despite successfully executing the action, when attempting to access the posted data from req, I a ...

Tips on activating the CSS style while typing using the onChange event in React

Is it possible to dynamically adjust the width of an input as we type in React? Currently, my input has a default width of 1ch. I would like it to increase or decrease based on the number of characters entered, so that the percentage sign stays at the end ...

Customize the theme of Ant Design for VueJS

I have successfully set up my Vue3 application with Tailwind and Ant Design. However, I am facing issues with customizing the Ant Design theme. I have been referring to this guide. When trying to customize the theme, I encountered the following error: Err ...

Toggle classes on button click

<div class='fixed_button homes hidden'> <a class='btn btn-primary homes'>Continue &rarr;</a> </div> Using jQuery Library $(".homes").on('click', function(){ $("choose_style").addClass(&apo ...

How to retrieve values from dynamically generated text boxes using ng-repeat in AngularJS

When using ng-repeat, I am able to display textboxes related to each item. Upon clicking the SaveAll button, I intend to retrieve all textbox values based on ITEM ID and save them to the database. <tr> <td> <table ng-repeat="item in ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

Tips for updating model data when integrating jQuery Data tables with ASP.NET MVC

Managing a large amount of data returned from JSON can be complex. To tackle this, I am utilizing jQuery dataTable for sorting, filtering, and pagination purposes. The functionality is working seamlessly for sorting, searching, and paginating the data. H ...

What is the best method for choosing an element that has been dynamically loaded through ajax

Wanting to streamline the editing process, I am looking for a way to load certain elements of a webpage dynamically, such as a sidebar and navbar, so that changes only need to be made in one place. Additionally, once these elements are loaded, I would like ...

What is preventing me from sending back an array of objects with an async function?

Working with node.js, my goal is to retrieve a list of bid and ask prices from a trading exchange website within an async function. While I can successfully log the object data using console.info() within the foreach statement on each iteration, when attem ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

Refreshing events in FullCalendar 5 using Vue.js's refetchEvents

I am currently integrating FullCalendar with Vue.js. My goal is to reload the events when the refreshCal() function is triggered, thereby rendering the calendar on the screen using refetchEvents. I have two main components: The Calendar: here is the code ...

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

Tips for creating a textarea element that resembles regular text format

I am working on creating an HTML list that allows users to edit items directly on the page and navigate through them using familiar keystrokes and features found in word processing applications. I envision something similar to the functionality of To achi ...

Issue with Bootstrap 4.2 modal: Unable to edit input fields, button cannot be clicked, modal does not close

https://i.sstatic.net/vHnVG.png https://i.sstatic.net/MhU3f.png Utilizing Bootstrap 4.2.1, I have a modal that opens via a specific link: <a href="#" data-toggle="modal" data-target="#inviteByEmailPopup" data-backdrop="false" data-keyboard="false"> ...