TypeError Cannot read property post of undefined

TypeError Cannot read property post of undefined

AngularJS: If you are trying to post data to the server using AngularJS http post and getting below error:

 TypeError: Cannot read property 'post' of undefined
    at new <anonymous> (http://localhost:8080/SpringMVCAJAXFormSubmit/:14:11)
    at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:35:36)
    at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:35:165)
    at $get (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:67:419)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:54:25
    at r (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:7:392)
    at N (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:53:396)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:256)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:273)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:46:377
  • It means $http has not been registered with controller. Below code will throw above exception:

AngularJS TypeError Cannot read property post of undefined

  • Solution: Register $http service to the controller will resolve the issue:

AngularJS TypeError Cannot read property post of undefined

  • Complete working code:
<!DOCTYPE html>
<html data-ng-app="myapp">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS Controller example</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">
	
	var app = angular.module('myapp', []);
	
		app.controller('myController',['$scope','$http', function($scope, $http) {
			$scope.name = "Java Honk";
			$scope.loading = true;
			  $http.post('submitForm.web', { foo: 'bar' }).success(function(response) {
			    $scope.response = response;
			    $scope.loading = false;
			});
		}]);
</script>
</head>
<body data-ng-controller="myController">
<form action="submitForm.web" method="post" id="submitForm">
	<p>
		<label for=name>Name:</label> <input type="text" data-ng-model="name">
	</p>
	<p>
		<label for=name>Date:</label>&nbsp;&nbsp;&nbsp;<input type="text" data-ng-model="dob" />
	</p>
	<p>
		<label for=name>Email:</label> <input type="date" data-ng-model="email" />
	</p>
	<p>
		<label for=name>Phone:</label> <input type="text" data-ng-model="phone" />
	</p>
	
	<p><input id="submit" type="submit" value="Submit"></p>
	<div>Hello, {{name}}!</div>
</form> 
</body>
</html>
  • For more information about submit post data using AngularJS please follow use this link 

Leave a Reply

Your email address will not be published. Required fields are marked *