TrinityTuts Tips

Post form data to server in AngularJs

Simple tip to send your form data to server using angular js and get that data in $_POST variable

<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
		<script type="text/javascript">
			var app = angular.module("myApp" , []);
			app.controller("sendForm" , function($scope, $http){
				$scope.saveData= function(){
					$scope.signError = false;
					$scope.signSuccess = false;
					var request = $http({
						method: "post",
						url:  "save.php",
						data: $.param($scope.data),  // pass in data as strings
						headers : { 'Content-Type': 'application/x-www-form-urlencoded',
							'X-Requested-With' : 'XMLHttpRequest'
						}
						// set the headers so angular passing info as form data (not request payload)
					});
					
					request.success(function (res) {
						console.log(res);
					});
					request.error(function(serverResponse, status, headers, config) {
						/* Error loading data */
					});	
				};
			});
		</script>
		
		<title>Sample</title>
	</head> 
	<body ng-app="myApp">
		<div  ng-controller="sendForm">
			<form method="post" ng-submit="saveData()">
				<div>
					<label>Name</label>
					<input ng-model="data.name">
				</div>
				<div class="md-block" flex-gt-xs>
					<label>Age</label>
					<input ng-model="data.age">
				</div>
				<div class="form-group">
					<button type="submit" class="btn btn-default">Save</button>
				</div>
			</form>
		</div>
		
	</body>
</html>

And you can print  send data save.php

<?php
print_r($_POST);

🙂