Last updated on July 31st, 2016 at 11:13 am
In my last post about Angular Js i will explain some basic of it, and now i am going to explain how we can communicate with server and post, receive data from server. I am using PHP back-end to handle my request here.
Now before we start send and receive data to server i want show some easy example in which we can perform basic operation like concatenate two input fields data in Angular, and show how to use multiple controllers in your app.
Using script in your Angular Js Application
Now if you know about jQuery or JavaScript you are familiar with <script> tag and know why we use, or if you don’t know then its ok we use this to write or jQuery/JavaScript functionality inside this tag like we wan’t to add some animation in our app we code inside it or if we need to add validation init. Now we also use this tag for Angular to perform some action based on our requirement
Example 1: Concatenate two value
<html> <head> <title>Angular JS Controller</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="mainApp" ng-controller="studentController"> Enter first name: <input type="text" ng-model="student.firstName"><br><br> Enter last name: <input type="text" ng-model="student.lastName"><br> <br> You are entering: {{student.fullName()}} </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Aneh", lastName: "Thakur", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
In above code inside a script tag
- I get my app using : angular.module(“appName”, []);
- Now using my app i find my controller like appVar.controller(‘<my_controller>’, <YOUR_FUNCTIONALITY>);
- Now using scope i get my fullname object and create a function so it can concatenate first and last name as shown above.
Communicating with server using AngularJs $http
In Angular, the basic building block for communication with server is $http service. The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequestobject or via JSONP.
This service provides basic functionalities like:
- GET
- POST
- HEAD
- DELETE
- PUT
- JSONP
Angular API uses the Promise interface based approach for server side communication. There are two method names, success and error for handling the response from the server.
Example to POST data to server in Angular Js
<html> <head> <title>Angular JS Controller</title> <!-- Add your angular here //--> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body ng-app="myApp"> <h2>Post Data</h2> <div id="container"> <div id="login" ng-controller='register'> <input type="name" size="40" ng-model="name"><br> <input type="email" size="40" ng-model="email"><br> <button ng-click="register()">Register</button><br> <pre id="response"> </pre> </div> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('register', function ($scope, $http) { /* * This method will be called on click event of button. */ $scope.register = function () { document.getElementById("response").textContent = ""; var request = $http({ method: "post", url: "getData.php", data: { name: $scope.name, email: $scope.email }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); /* Check whether the HTTP Request is successful or not. */ request.success(function (data) { document.getElementById("response").textContent = "Raw Response: "+data; }); request.error(function(serverResponse, status, headers, config) { alert("failure"); }); } }); </script> </body> </html>
In above code is very easy to use. Using $scope i get click event and run method and post data to server. In this we send JSON Object to server so there is some change to handle this data over server as compare to normal data.
<?php $postdata = file_get_contents("php://input"); $request = json_decode($postdata); echo $request->name; echo $request->email; ?>
that it, i am not going to explain further process over server because i hope u know how to save data further once you get data :-).
Example to GET data from server in Angular Js
In this example i show you how to load data from server using get method
<html> <head> <title>Angular JS Controller</title> <!-- Add your angular here //--> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body ng-app="myApp"> <h2>Load data on button click</h2> <div ng-app="myApp" ng-controller="getJsonDataOnClick"> <button ng-click="getData();">Load Data</button> <ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.status }} </li> </ul> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('getJsonDataOnClick', function ($scope, $http) { $scope.getData = function () { $http.get("jsonData.php").success(function(response) {$scope.names = response.records;}); } }); </script> </body> </html>
And at server end we need to convert our response into JSON Response like this
<?php $array['records'] = array(array("name" => "aneh thakur", "status" => "Love think code"), array("name" => "Amit Rana", "status" => "Happy")); echo json_encode($array);
Above example are easy to implement and are very basic to start but very easy to learn basic communication between server and Angular. I share download link above, download link contain some more example to learn about Angular Js hope you like.
Happy coding 🙂