Error: Attempting to access property 'post' of an undefined variable is not possible

Encountering an Error:

TypeError: Cannot read property 'post' of undefined
    at postName (http://127.0.0.1:9000/scripts/controllers/main.js:28:12)
    at Scope.$scope.submit (http://127.0.0.1:9000/scripts/controllers/main.js:10:7)
    at http://127.0.0.1:9000/bower_components/angular/angular.js:10348:21
    at http://127.0.0.1:9000/bower_components/angular/angular.js:18333:17
    at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12175:28)
    at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12273:23)
    at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
    at HTMLFormElement.<anonymous> (http://127.0.0.1:9000/bower_components/angular/angular.js:18332:21)
    at HTMLFormElement.jQuery.event.dispatch (http://127.0.0.1:9000/bower_components/jquery/dist/jquery.js:4641:9)
    at HTMLFormElement.elemData.handle (http://127.0.0.1:9000/bower_components/jquery/dist/jquery.js:4309:46) angular.js:9563(anonymous function) angular.js:9563(anonymous function) angular.js:7004Scope.$apply angular.js:12275$delegate.__proto__.$apply VM1976:855(anonymous function) angular.js:18332jQuery.event.dispatch jquery.js:4641elemData.handle

The content of my main.js file:

'use strict';

angular.module('sayHiApp')
  .controller('MainCtrl', function ($scope) {

    // Takes form input
    $scope.submit = function() {

      // Sending data to webservice via POST
      postName($scope.input);

      // Retrieving data from webservice
      var name = getName();

      // DEBUG: Combining greeting message
      $scope.greeting = 'Sup ' + name + ' !';

    };

    function postName ($scope, $http, dataToPost) {

      $http.post('/name', dataToPost).
      success(function(data) {
        $scope.error = false;
        $scope.data = data;
      }).
      error(function(data) {
        $scope.error = true;
        $scope.data = data;
      });
    }

    // Fetching name from webservice
    function getName ($scope, $http) {

      $http.get('/name').
      success(function(data) {
        $scope.error = false;
        $scope.data = data;

        return data;
      }).
      error(function(data) {
        $scope.error = true;
        $scope.data = data;

        return 'error name';
      });

    }

  });

I am confused about the root cause of this error. If it pertains to the 'post' method on '$http', I would appreciate any clarification.. Thank you in advance for your assistance :)

Answer №1

Here, we are discussing the use of the 'post' method in relation to '$http'.

In order for angular to inject $http into the controller function, you must add it as a parameter (similar to how you did with $scope).

I made a modification to your code by removing the $scope and $http parameters from the inner functions since they are already accessible due to closure.

angular.module('sayHiApp')
  .controller('MainCtrl', function ($scope, $http) {

// Accepts form input
$scope.submit = function() {

  // Sends data via POST request to webservice
  postName($scope.input);

  // Retrieves data from webservice
  var name = getName();

  // DEBUG: Creates greeting message
  $scope.greeting = 'Sup ' + name + ' !';

};

function postName (dataToPost) {

  $http.post('/name', dataToPost).
  success(function(data) {
    $scope.error = false;
    $scope.data = data;
  }).
  error(function(data) {
    $scope.error = true;
    $scope.data = data;
  });
}

// Retrieves name from webservice
function getName () {

  $http.get('/name').
  success(function(data) {
    $scope.error = false;
    $scope.data = data;

    return data;
  }).
  error(function(data) {
    $scope.error = true;
    $scope.data = data;

    return 'error name';
  });
}
});

Answer №2

In order to simplify the code, the postName function does not require the variables $scope and $http to be passed as arguments. All that is needed is the dataToPost. The function can be written as follows:

function postName(dataToPost) {

  $http.post('/name', dataToPost).
  success(function(data) {
    $scope.error = false;
    $scope.data = data;
  }).
  error(function(data) {
    $scope.error = true;
    $scope.data = data;
  });
}

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

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Add values to each entry in a subarray

let b = []; this.state.sidejobs.forEach((user) => { console.log(user); if (!b.hasOwnProperty(user.jobworker)) b[user.jobworker] = 0; b[user.jobworker] += user.duration; }); I have a query regarding splitting and adding durations in entries where ...

How can I make sure my rows are properly aligned using the Grid

Looking at the image below, I am attempting to align "Ticket Number" and "Email" using a Grid: View My Result Image <Grid container direction="row" justifyContent="flex-start" alignItems="stretch" style={{ pad ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Sending a massive video file to a node.js server and saving it in AWS S3 with ReactJS

I am currently in the process of creating an OTT platform, but I have encountered a problem while attempting to upload large files to the server. I initially attempted to store the file in a temporary folder using multer and then utilize aws-sdk s3.upload. ...

Introducing a new feature in React-Select: enabling copy-paste functionality for the multi-select text

Incorporating a react-select component (specifically generated using CreatableSelect) into my project has been quite beneficial. This multi select text input feature allows users to conveniently add keywords as options. While the current functionality is ...

Issue with react-table: data not displayed upon initial load and after refreshing the page

I am currently working on a project that involves rendering table data from an API using fetch. However, I'm encountering an issue where the table data disappears when navigating to a different page or refreshing the current page. Any assistance or ad ...

Issue with scrolling in Droppable container on JQuery UI interface

I've encountered an issue with JQuery UI. In my code snippet, I can drag elements onto fields and when hovering over a field, it gets highlighted in green. However, I recently added the functionality to scroll while dragging. Now, I can scroll up and ...

Is it advantageous to have multiple AngularJS applications for a single website?

As I work on developing my website, I am considering structuring it into several main pages. These pages would essentially operate independently, but would share session data such as the session ID and logged-in username. Initially, my plan was to create ...

Connect the CSS active state to a JavaScript event

.el:active{ background:red; } Is there a way to associate the above CSS active state with a JavaScript event, like this: $('.el').on('active', function(){ img.show(); }); I want the image to remain visible when el is presse ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Guide to setting up ajax to parse the text input and generate a table

Strange dilemma I've been grappling with for the past couple of days. Definitely a novice at this. Here's my code: $(document).ready(function() { var table = $('#table1').DataTable({ "ajax" : { url ...

Absence of Callback Function Detected

function handleRequest(req, res) { if (req.body.widget_name) { console.log(req.body.widget_name); } var fs = require('fs'); var data = fs.readdir("corpdashboard/dashboards", 'UTF-8', function (err, files) { ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

Handling onclick events in Scrapy Splash: A comprehensive guide

I am attempting to extract data from the following website I have managed to receive a response, but I am unsure how to access the inner data of the items below for scraping: It seems that accessing the items requires handling JavaScript and pagination. ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Iterate through each checkbox within a specific classed div to check for selected options

Is there a way to loop through specific checkboxes with a particular class inside a div without assigning individual IDs to each one? I want to avoid the manual process of adding IDs. Below is the code snippet: JS <script> function calculate() { ...

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

"Developing an Ionic app that utilizes Angular to send POST requests to a socket

I had a functional ionic app that communicated with a node server running a socket.io server. The socket server is receiving the POST request, but the body is empty. It used to work flawlessly. I can successfully send data using a REST client (like PAW o ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...