The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files:

  1. /app/view1/view1.js 'use strict';

    angular.module('myApp.view1', ['ngRoute'])
    
    .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
      });
    }])
    
    
    .controller('View1Ctrl', ['$scope', '$http',
      function ($scope, $http) {
        $http.get('/app/data/events.json').success(function(data) {
          $scope.events = data.record;
        }).error(function(data, status){
            alert("error "+data+' | '+status);
        });
    
        $scope.orderProp = 'date';
      }]);
    
  2. /app/view1/view1.html

    p>Available Events</p>
    
    <div ng-controller="EventListController">
      <ul>
        <li ng-repeat="event in events">
            <p>{{event.name}}</p>
            <div>{{event.location}}</div>
            <div>{{event.description}}</div>
            <div>{{event.date}}</div>
    
        </li>
    
      </ul>
    
     <p>Total number of events: {{events.size}}</p>
    </div>
    

However, upon displaying the page, I received an error message that says:

"error undefined | undefined".

Despite checking through the code multiple times, I couldn't figure out why the JSON file is not loading. Interestingly, when I directly access http://localhost:8000/app/data/events.json in the browser, the JSON data is successfully loaded.

This predicament leads me to ask: what could be causing the failure to load the JSON file?

Answer №1

Utilizing $http methods in the following manner is recommended:

// Example of a simple GET request:
$http.get('url').then(function successCallback(response) {
    // This callback will be executed asynchronously
    // once the response is received
  }, function errorCallback(response) {
    // Executed asynchronously if an error occurs
    // or if the server returns a response with an error status.
  });

The variables data and status are currently undefined in your code.

To rectify this issue, consider updating your code as shown below:

 $http.get('/app/data/events.json')
 .then(function successCallback(response) {
      $scope.events = data.record;
  },
  function errorCallback(response) {
      alert(response);
  });

This adjustment should help resolve your problem.

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

Setting up a secure Node.JS HTTPS server on Cloud9 IDE

Wondering if it's possible to set up a Node.js https server in the cloud9 IDE? Check out this example of a basic https server setup in Node.js. var https = require('https'); var fs = require('fs'); var app = require('./app& ...

The process of deleting lines from an image using Javascript

If I have an image of a data-table and I want to eliminate all the grid lines (defined as continuous vertical or horizontal pixels), is there a way to achieve this using Javascript's image data manipulation? I envision looping through a 2D array conta ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

Get a file from a node.js web server by clicking a button to initiate the download

I am a beginner in nodejs and I am working on creating a web server using nodejs to host some static files. Here is the code I have used for this purpose: var http = require('http'); var finalhandler = require('finalhandler'); var ser ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

How can we eliminate identical elements from an array in JavaScript and increment the count of other objects?

I currently have 1 object retrieved from local storage, but it seems to contain some duplicates. What is the easiest way to remove these duplicates? The array object I am working with is called "mainchart". function check() { for (let i = 0; i < main ...

Disappearing Bootstrap 3 Dropdown Issue Caused by Tab Click

There is an issue with the drop-down menu I created: When I click on tabs like ALL or FILM, it closes all elements. To reopen, I have to click again on the button PRODUCT.dropdown-toggle. The code example looks like this: var App = function () { ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Storing content from external files in Angular 1.x templateCache

I am currently utilizing the Angular templateCache, following the example set in Angular's documentation. var myApp = angular.module('myApp', []); myApp.run(function($templateCache) { $templateCache.put('templateId.html', ' ...

Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have ...

Submitting information retrieved through an AJAX request to a MySQL database using PHP

I have implemented a JavaScript function to collect and display data, but now I am looking to save this data into a MySQL database for tracking purposes. I attempted to connect to the MySQL database locally using PHP code, but encountered some issues. I be ...

Transforming a JSON object into a case class with a single field: a step-by-step guide

When dealing with Play 2.1, using reads to convert Json into objects is a common practice. However, it becomes tricky when working with case classes that have only one field. The usual method for multiple fields doesn't apply in this scenario as &apos ...

Rate of AngularJS Dirty Checking

Recently, I was diving into an article to gain a deeper understanding of the inner workings of angular.js. One concept that stood out to me was 'dirty checking($digest)'. I began to wonder at what frequency the watchers are actively listening f ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Displaying image previews in AngularJS from file inputs

Could anyone kindly explain to me why this code is not functioning correctly? Here is my preview area: <div class="preview"><img src="" alt=""></div> and here is my input: <input type="file" file-input> along with my ...

Filtering elements in a table using jQuery

Can anyone provide a solution to display students without a class and hide the rest (where td Class-name is empty) using only jQuery or JS? I tried looking in the documentation but got lost. Any help would be appreciated. Example: table image The table ...

The Bootstrap modal causes the scrollbar to vanish upon closure

Despite trying numerous solutions and hacks on this issue from StackOverflow, none of them seem to work for me. Currently, I am utilizing a modal for the login process in Meteor (e.g. using Facebook login service) which triggers a callback upon successful ...

Tips for implementing the f11 effect with a delay of 5 seconds after pressing a key in JavaScript or jQuery

Is there a way to activate the F11 effect only 5 seconds after pressing a key using JavaScript or jQuery? ...

(RESPOND) Configuring a preset option for a Dropdown selection field

I am currently developing a frontend to demonstrate the behavior of a CRUD RESTful API. One specific requirement is that when the user selects the option "GET", the default value in the dropdown field labeled "Order-by" should be set to "Name". However, fo ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...