Skip to main content

3 Ways to use angular $http service with php processing

Angular $http service is used to send asynchronous http request to the server. To learn how to use $http service with php, we will create a simple app using form directive. This app will take two numbers and send the these number to php server for their sum. Here we will use php code to process the data and return the sum.

Let's jump into the app. Here is front end HTML code for our app. We are using twitter bootstrap to for awesome look of our app:

Way 1:

HTML Code:

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <title>Find Sum</title>
   <link rel="stylesheet" href="css/bootstrap.min.css">
 </head>
 <body ng-app="myApp">
   <div class="container" ng-controller="myAppCtrl">
     <div class="row">
       <div class="col-sm-4 col-sm-push-4">
         <h1 class="text-center text-primary">FIND SUM</h1>
         <form name="sumForm">
           <div class="form-group">
            <label for="a">A:</label>
            <input ng-model="value.a" type="number" id="a" name="a" class="form-control" placeholder="A" required>
           </div>
           <div class="form-group">
            <label for="b">B:</label>
            <input ng-model="value.b" type="number" class="form-control" id="b" name="b" placeholder="B" required>
           </div>
           <input type="submit" ng-click="sum()" ng-disabled="sumForm.$invalid" class="btn btn-primary" value="SUM"></input>
           <h4>Sum = {{result}}</h4>
         </form>
       </div> 
     </div>
   </div>
 <script src="js/jquery-3.2.1.min.js"></script>
 <script src="js/angular.min.js"></script>
 <script src="script.js"></script>
 </body>
</html>
We have used form directive and define two input boxes which will get value of A and B. On clicking the submit button sum() function will  trigger which is define on $scope into the myAppCtrl controller. Here is code for the javascript:


Javascript Code (script.js):

var app = angular.module('myApp',[]);
app.controller('myAppCtrl', ['$scope', '$http', function($scope, $http){
  $scope.result = 0;
  $scope.sum = function(){
  $http({
        method : 'POST',
        url : 'php/sum.php',
        data : $scope.value
  })
 .then(
      function(response){
        $scope.result = response.data.sum;
      });
 };
}]);
Here we have used $http POST method and request parameter are sent using 'data' parameter of the configuration object of $http. The responded sum value is assigned to $scope.result model. Now see how to process the POST data at server using php code.

Php Code (sum.php):

<?php
  $post = json_decode(file_get_contents(('php://input')));
  $data = array();
  $data['sum'] = $post->a + $post->b;
  echo json_encode($data);
?>

As we know that the default header 'Content-Type' of the POST request in angular $http service is 'application/json', so in php code we used file_get_contents method to read the json data sent by the user and used json_decode method to convert it into object . After conversion we can easily access the value of a and b and process it to sent the sum of them.



Way 2:

If you still wanted to use the $_POST array into your php code, here is a way in way 2. You will be able to use the $_POST array into your code. There is some changes in JavaScropt and PHP code and HTML code will remain same as in way 1. Here is javascript code for way 2.

Javascript Code (script.js):

var app = angular.module('myApp',[]);

app.config(function($httpProvider){
  $httpProvider.defaults.headers.post = {'Content-Type':'application/x-www-form-urlencoded'};
});

app.controller('myAppCtrl', ['$scope', '$http', '$httpParamSerializerJQLike',
  function($scope, $http, $httpParamSerializerJQLike){
   $scope.result = 0;
   $scope.sum = function(){
      $http({
        method : 'POST',
        data : $httpParamSerializerJQLike($scope.value), //when not using jquery
        url : 'php/temp.php'
      })
      .then(
        function(response){
          $scope.result = response.data.sum;
        }
      );
    };
}]);
Here we have changed the 'Content-Type' of default header for POST methed provided by $httpProvider within the config function of the angular app. We have set the 'Content-Type' to 'application/x-www-form-urlencoded', so that POST request will send the data into urlencode form so that sent data can be accessed using $_POST array.


Php Code (sum.php):

<?php
$data = array();
if(isset($_POST)){
  $data['sum'] = $_POST['a'] + $_POST['b'];
  echo json_encode($data);
}
?>
Now, we are able to use the $_POST array to access the sent parameter.

Way 3:

If you are defining many functions which send $http request, it is bulky to configure $http configuration object each time. The code will look dirty as each time you send a $http request you have to repeat the configuration object and parameter to the controller function. Here is way 3 to remedy to this situation. We will define our own service using factory method of angular which is built upon a $http service and we don't have to configure our app using config function each time when we define an app. The way 3 code for HTML and PHP will remain same and their is change in javascript code where define our own service. Here is code for javascript;

Javascript Code (script.js):

var app = angular.module('myApp',[]);

app.factory('$xhr',function($http, $httpParamSerializerJQLike){
  return{
    post : function(url,data){
      return $http({
        method : 'POST',
        url : url,
        data : $httpParamSerializerJQLike(data),
        headers : {'Content-Type':'application/x-www-form-urlencoded'}
      });
    },
    get: function(url){
      return $http({
        method : 'GET',
        url : url
      });
    }
  };
});

app.controller('myAppCtrl', function($scope, $xhr){
   $scope.sum = function(){
    $xhr.post('php/temp.php', $scope.value)
    .then(function(res){
      $scope.result = res.data.sum;
    });
   };
});
Here we have defined our custom service $xhr using factory method of angular. It takes $http and $httpParamSerializerJQLike as parameter. We defined post and get method on $xhr service. Header and sent parameter are set in configuration object of $http service.

And then we use $xhr service into our myAppCtrl and use it to send the $http request using arguments url and data as $xhr(url,data).

One more important thing I would like to say that I am sorry for my bad English.

Comments

Popular posts from this blog

Code Syntax Highlighting on Blogger using Prismjs

Prismjs is developed by Lea Verou. It is a lightweight, extensible syntax highlighter, built with modern web standards in mind. It’s used in thousands of websites, including some of those you visit daily.Today, we will see how to use the prismjs on blogger to highlight our codes. It very easy and step by step process to follow: Goto to this link and get the personalized links for prismjs or simply copy the links given below: <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/themes/prism-coy.min.css" rel="stylesheet"></link> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/prism.min.js"></script> Goto Theme > Edit HTML and paste the links before the closing </head> section as shown below: Default prism.min.js file contain the functionality to highlight the code for only HTML, CSS and JS code. If you wish to use other language to highlight, you have to paste the link for that langu...

$parsers and $formatters in Angularjs

$parsers and $formatters are array of function defined on ngModelController . When there is change in values (view or model), the value is passed through the $parsers or $formatters pipeline to convert it according to the needs. $parsers (View to Model): $parsers is an array of function which executes when there is change in view  value ( $veiwValue ), usually via user input. $parsers cause the conversion of view value into the form desirable to assign in model value. The value is passed through each $parsers function and the return value of one function is passed to next function. Last return value is passed to $validators and after validation the value is assigned to model. These $parsers functions are called array order (i.e. index 0 to n). $parsers are not called when there is change in model value programmatically. $parsers function must return some value. If it not, causes parse error and model value is set to undefined . Let's see the simple ...

Automatic Slashing the Date Input using Angularjs

We define a directive that will automatically slash the input field as user typein the date. The directive have following capabiltiy: The directive will append slash '/' when input field has 2 or 5 characters. The input will accept only 10 characters (dd/mm/yyyy). Validity of date provide will not be checked. When the backspace is pressed it will remove the last two character if last character is slash. Otherwise it will remove last character from the input field. The input will not accept characters other than numbers (0 to 9). Let's jump into the code. We will use bootstrap for awesome look: HTML Code: <div class="container" ng-app="myApp" ng-controller="myAppCtrl"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <form class="form-horizontal"> <h4 class="bg-primary">Auto Slashing Date using Angularjs Directive</h4> <div class=...